babylon.viewer.max.js 5.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478
  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.updateTransformMatrix();
  24044. if (camera._alternateCamera) {
  24045. this.updateAlternateTransformMatrix(camera._alternateCamera);
  24046. this._alternateRendering = true;
  24047. }
  24048. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  24049. // Meshes
  24050. this._evaluateActiveMeshes();
  24051. // Software skinning
  24052. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  24053. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  24054. mesh.applySkeleton(mesh.skeleton);
  24055. }
  24056. // Render targets
  24057. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24058. var needsRestoreFrameBuffer = false;
  24059. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  24060. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  24061. }
  24062. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  24063. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  24064. }
  24065. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  24066. this._intermediateRendering = true;
  24067. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24068. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24069. var renderTarget = this._renderTargets.data[renderIndex];
  24070. if (renderTarget._shouldRender()) {
  24071. this._renderId++;
  24072. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24073. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24074. }
  24075. }
  24076. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24077. this._intermediateRendering = false;
  24078. this._renderId++;
  24079. needsRestoreFrameBuffer = true; // Restore back buffer
  24080. }
  24081. // Render EffecttLayer Texture
  24082. var stencilState = this._engine.getStencilBuffer();
  24083. var renderEffects = false;
  24084. var needStencil = false;
  24085. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24086. this._intermediateRendering = true;
  24087. for (var i = 0; i < this.effectLayers.length; i++) {
  24088. var effectLayer = this.effectLayers[i];
  24089. if (effectLayer.shouldRender() &&
  24090. (!effectLayer.camera ||
  24091. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24092. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24093. renderEffects = true;
  24094. needStencil = needStencil || effectLayer.needStencil();
  24095. var renderTarget = effectLayer._mainTexture;
  24096. if (renderTarget._shouldRender()) {
  24097. this._renderId++;
  24098. renderTarget.render(false, false);
  24099. needsRestoreFrameBuffer = true;
  24100. }
  24101. }
  24102. }
  24103. this._intermediateRendering = false;
  24104. this._renderId++;
  24105. }
  24106. if (needsRestoreFrameBuffer) {
  24107. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24108. }
  24109. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24110. // Prepare Frame
  24111. this.postProcessManager._prepareFrame();
  24112. // Backgrounds
  24113. var layerIndex;
  24114. var layer;
  24115. if (this.layers.length) {
  24116. engine.setDepthBuffer(false);
  24117. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24118. layer = this.layers[layerIndex];
  24119. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24120. layer.render();
  24121. }
  24122. }
  24123. engine.setDepthBuffer(true);
  24124. }
  24125. // Activate effect Layer stencil
  24126. if (needStencil) {
  24127. this._engine.setStencilBuffer(true);
  24128. }
  24129. // Render
  24130. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24131. this._renderingManager.render(null, null, true, true);
  24132. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24133. // Restore effect Layer stencil
  24134. if (needStencil) {
  24135. this._engine.setStencilBuffer(stencilState);
  24136. }
  24137. // Bounding boxes
  24138. if (this._boundingBoxRenderer) {
  24139. this._boundingBoxRenderer.render();
  24140. }
  24141. // Lens flares
  24142. if (this.lensFlaresEnabled) {
  24143. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24144. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24145. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24146. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24147. lensFlareSystem.render();
  24148. }
  24149. }
  24150. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24151. }
  24152. // Foregrounds
  24153. if (this.layers.length) {
  24154. engine.setDepthBuffer(false);
  24155. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24156. layer = this.layers[layerIndex];
  24157. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24158. layer.render();
  24159. }
  24160. }
  24161. engine.setDepthBuffer(true);
  24162. }
  24163. // Effect Layer
  24164. if (renderEffects) {
  24165. engine.setDepthBuffer(false);
  24166. for (var i = 0; i < this.effectLayers.length; i++) {
  24167. if (this.effectLayers[i].shouldRender()) {
  24168. this.effectLayers[i].render();
  24169. }
  24170. }
  24171. engine.setDepthBuffer(true);
  24172. }
  24173. // Finalize frame
  24174. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24175. // Reset some special arrays
  24176. this._renderTargets.reset();
  24177. this._alternateRendering = false;
  24178. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24179. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24180. };
  24181. Scene.prototype._processSubCameras = function (camera) {
  24182. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24183. this._renderForCamera(camera);
  24184. return;
  24185. }
  24186. // rig cameras
  24187. for (var index = 0; index < camera._rigCameras.length; index++) {
  24188. this._renderForCamera(camera._rigCameras[index], camera);
  24189. }
  24190. this.activeCamera = camera;
  24191. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24192. };
  24193. Scene.prototype._checkIntersections = function () {
  24194. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24195. var sourceMesh = this._meshesForIntersections.data[index];
  24196. if (!sourceMesh.actionManager) {
  24197. continue;
  24198. }
  24199. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24200. var action = sourceMesh.actionManager.actions[actionIndex];
  24201. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24202. var parameters = action.getTriggerParameter();
  24203. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24204. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24205. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24206. if (areIntersecting && currentIntersectionInProgress === -1) {
  24207. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24208. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24209. sourceMesh._intersectionsInProgress.push(otherMesh);
  24210. }
  24211. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24212. sourceMesh._intersectionsInProgress.push(otherMesh);
  24213. }
  24214. }
  24215. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24216. //They intersected, and now they don't.
  24217. //is this trigger an exit trigger? execute an event.
  24218. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24219. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24220. }
  24221. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24222. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24223. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24224. }
  24225. }
  24226. }
  24227. }
  24228. }
  24229. };
  24230. Scene.prototype.render = function () {
  24231. if (this.isDisposed) {
  24232. return;
  24233. }
  24234. this._activeParticles.fetchNewFrame();
  24235. this._totalVertices.fetchNewFrame();
  24236. this._activeIndices.fetchNewFrame();
  24237. this._activeBones.fetchNewFrame();
  24238. this._meshesForIntersections.reset();
  24239. this.resetCachedMaterial();
  24240. this.onBeforeAnimationsObservable.notifyObservers(this);
  24241. // Actions
  24242. if (this.actionManager) {
  24243. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24244. }
  24245. //Simplification Queue
  24246. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24247. this.simplificationQueue.executeNext();
  24248. }
  24249. if (this._engine.isDeterministicLockStep()) {
  24250. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24251. var defaultFPS = (60.0 / 1000.0);
  24252. var defaultFrameTime = 1000 / 60; // frame time in MS
  24253. if (this._physicsEngine) {
  24254. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24255. }
  24256. var stepsTaken = 0;
  24257. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24258. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24259. internalSteps = Math.min(internalSteps, maxSubSteps);
  24260. do {
  24261. this.onBeforeStepObservable.notifyObservers(this);
  24262. // Animations
  24263. this._animationRatio = defaultFrameTime * defaultFPS;
  24264. this._animate();
  24265. this.onAfterAnimationsObservable.notifyObservers(this);
  24266. // Physics
  24267. if (this._physicsEngine) {
  24268. this.onBeforePhysicsObservable.notifyObservers(this);
  24269. this._physicsEngine._step(defaultFrameTime / 1000);
  24270. this.onAfterPhysicsObservable.notifyObservers(this);
  24271. }
  24272. this.onAfterStepObservable.notifyObservers(this);
  24273. this._currentStepId++;
  24274. stepsTaken++;
  24275. deltaTime -= defaultFrameTime;
  24276. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24277. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24278. }
  24279. else {
  24280. // Animations
  24281. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24282. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24283. this._animate();
  24284. this.onAfterAnimationsObservable.notifyObservers(this);
  24285. // Physics
  24286. if (this._physicsEngine) {
  24287. this.onBeforePhysicsObservable.notifyObservers(this);
  24288. this._physicsEngine._step(deltaTime / 1000.0);
  24289. this.onAfterPhysicsObservable.notifyObservers(this);
  24290. }
  24291. }
  24292. // update gamepad manager
  24293. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24294. this._gamepadManager._checkGamepadsStatus();
  24295. }
  24296. // Before render
  24297. this.onBeforeRenderObservable.notifyObservers(this);
  24298. // Update Cameras
  24299. if (this.activeCameras.length > 0) {
  24300. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24301. var camera = this.activeCameras[cameraIndex];
  24302. camera.update();
  24303. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24304. // rig cameras
  24305. for (var index = 0; index < camera._rigCameras.length; index++) {
  24306. camera._rigCameras[index].update();
  24307. }
  24308. }
  24309. }
  24310. }
  24311. else if (this.activeCamera) {
  24312. this.activeCamera.update();
  24313. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24314. // rig cameras
  24315. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  24316. this.activeCamera._rigCameras[index].update();
  24317. }
  24318. }
  24319. }
  24320. // Customs render targets
  24321. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24322. var engine = this.getEngine();
  24323. var currentActiveCamera = this.activeCamera;
  24324. if (this.renderTargetsEnabled) {
  24325. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24326. this._intermediateRendering = true;
  24327. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24328. var renderTarget = this.customRenderTargets[customIndex];
  24329. if (renderTarget._shouldRender()) {
  24330. this._renderId++;
  24331. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24332. if (!this.activeCamera)
  24333. throw new Error("Active camera not set");
  24334. // Viewport
  24335. engine.setViewport(this.activeCamera.viewport);
  24336. // Camera
  24337. this.updateTransformMatrix();
  24338. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24339. }
  24340. }
  24341. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24342. this._intermediateRendering = false;
  24343. this._renderId++;
  24344. }
  24345. // Restore back buffer
  24346. if (this.customRenderTargets.length > 0) {
  24347. engine.restoreDefaultFramebuffer();
  24348. }
  24349. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24350. this.activeCamera = currentActiveCamera;
  24351. // Procedural textures
  24352. if (this.proceduralTexturesEnabled) {
  24353. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24354. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24355. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24356. if (proceduralTexture._shouldRender()) {
  24357. proceduralTexture.render();
  24358. }
  24359. }
  24360. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24361. }
  24362. // Clear
  24363. if (this.autoClearDepthAndStencil || this.autoClear) {
  24364. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24365. }
  24366. // Shadows
  24367. if (this.shadowsEnabled) {
  24368. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24369. var light = this.lights[lightIndex];
  24370. var shadowGenerator = light.getShadowGenerator();
  24371. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24372. var shadowMap = (shadowGenerator.getShadowMap());
  24373. if (this.textures.indexOf(shadowMap) !== -1) {
  24374. this._renderTargets.push(shadowMap);
  24375. }
  24376. }
  24377. }
  24378. }
  24379. // Depth renderer
  24380. for (var key in this._depthRenderer) {
  24381. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24382. }
  24383. // Geometry renderer
  24384. if (this._geometryBufferRenderer) {
  24385. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24386. }
  24387. // RenderPipeline
  24388. if (this._postProcessRenderPipelineManager) {
  24389. this._postProcessRenderPipelineManager.update();
  24390. }
  24391. // Multi-cameras?
  24392. if (this.activeCameras.length > 0) {
  24393. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24394. if (cameraIndex > 0) {
  24395. this._engine.clear(null, false, true, true);
  24396. }
  24397. this._processSubCameras(this.activeCameras[cameraIndex]);
  24398. }
  24399. }
  24400. else {
  24401. if (!this.activeCamera) {
  24402. throw new Error("No camera defined");
  24403. }
  24404. this._processSubCameras(this.activeCamera);
  24405. }
  24406. // Intersection checks
  24407. this._checkIntersections();
  24408. // Update the audio listener attached to the camera
  24409. if (BABYLON.AudioEngine) {
  24410. this._updateAudioParameters();
  24411. }
  24412. // After render
  24413. if (this.afterRender) {
  24414. this.afterRender();
  24415. }
  24416. this.onAfterRenderObservable.notifyObservers(this);
  24417. // Cleaning
  24418. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24419. var data = this._toBeDisposed.data[index];
  24420. if (data) {
  24421. data.dispose();
  24422. }
  24423. this._toBeDisposed[index] = null;
  24424. }
  24425. this._toBeDisposed.reset();
  24426. if (this.dumpNextRenderTargets) {
  24427. this.dumpNextRenderTargets = false;
  24428. }
  24429. this._activeBones.addCount(0, true);
  24430. this._activeIndices.addCount(0, true);
  24431. this._activeParticles.addCount(0, true);
  24432. };
  24433. Scene.prototype._updateAudioParameters = function () {
  24434. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24435. return;
  24436. }
  24437. var listeningCamera;
  24438. var audioEngine = BABYLON.Engine.audioEngine;
  24439. if (this.activeCameras.length > 0) {
  24440. listeningCamera = this.activeCameras[0];
  24441. }
  24442. else {
  24443. listeningCamera = this.activeCamera;
  24444. }
  24445. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24446. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24447. // for VR cameras
  24448. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24449. listeningCamera = listeningCamera.rigCameras[0];
  24450. }
  24451. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24452. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24453. cameraDirection.normalize();
  24454. // To avoid some errors on GearVR
  24455. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24456. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24457. }
  24458. var i;
  24459. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24460. var sound = this.mainSoundTrack.soundCollection[i];
  24461. if (sound.useCustomAttenuation) {
  24462. sound.updateDistanceFromListener();
  24463. }
  24464. }
  24465. for (i = 0; i < this.soundTracks.length; i++) {
  24466. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24467. sound = this.soundTracks[i].soundCollection[j];
  24468. if (sound.useCustomAttenuation) {
  24469. sound.updateDistanceFromListener();
  24470. }
  24471. }
  24472. }
  24473. }
  24474. };
  24475. Object.defineProperty(Scene.prototype, "audioEnabled", {
  24476. // Audio
  24477. get: function () {
  24478. return this._audioEnabled;
  24479. },
  24480. set: function (value) {
  24481. this._audioEnabled = value;
  24482. if (BABYLON.AudioEngine) {
  24483. if (this._audioEnabled) {
  24484. this._enableAudio();
  24485. }
  24486. else {
  24487. this._disableAudio();
  24488. }
  24489. }
  24490. },
  24491. enumerable: true,
  24492. configurable: true
  24493. });
  24494. Scene.prototype._disableAudio = function () {
  24495. var i;
  24496. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24497. this.mainSoundTrack.soundCollection[i].pause();
  24498. }
  24499. for (i = 0; i < this.soundTracks.length; i++) {
  24500. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24501. this.soundTracks[i].soundCollection[j].pause();
  24502. }
  24503. }
  24504. };
  24505. Scene.prototype._enableAudio = function () {
  24506. var i;
  24507. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24508. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  24509. this.mainSoundTrack.soundCollection[i].play();
  24510. }
  24511. }
  24512. for (i = 0; i < this.soundTracks.length; i++) {
  24513. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24514. if (this.soundTracks[i].soundCollection[j].isPaused) {
  24515. this.soundTracks[i].soundCollection[j].play();
  24516. }
  24517. }
  24518. }
  24519. };
  24520. Object.defineProperty(Scene.prototype, "headphone", {
  24521. get: function () {
  24522. return this._headphone;
  24523. },
  24524. set: function (value) {
  24525. this._headphone = value;
  24526. if (BABYLON.AudioEngine) {
  24527. if (this._headphone) {
  24528. this._switchAudioModeForHeadphones();
  24529. }
  24530. else {
  24531. this._switchAudioModeForNormalSpeakers();
  24532. }
  24533. }
  24534. },
  24535. enumerable: true,
  24536. configurable: true
  24537. });
  24538. Scene.prototype._switchAudioModeForHeadphones = function () {
  24539. this.mainSoundTrack.switchPanningModelToHRTF();
  24540. for (var i = 0; i < this.soundTracks.length; i++) {
  24541. this.soundTracks[i].switchPanningModelToHRTF();
  24542. }
  24543. };
  24544. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  24545. this.mainSoundTrack.switchPanningModelToEqualPower();
  24546. for (var i = 0; i < this.soundTracks.length; i++) {
  24547. this.soundTracks[i].switchPanningModelToEqualPower();
  24548. }
  24549. };
  24550. /**
  24551. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  24552. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  24553. * @returns the created depth renderer
  24554. */
  24555. Scene.prototype.enableDepthRenderer = function (camera) {
  24556. camera = camera || this.activeCamera;
  24557. if (!camera) {
  24558. throw "No camera available to enable depth renderer";
  24559. }
  24560. if (!this._depthRenderer[camera.id]) {
  24561. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, BABYLON.Engine.TEXTURETYPE_FLOAT, camera);
  24562. }
  24563. return this._depthRenderer[camera.id];
  24564. };
  24565. /**
  24566. * Disables a depth renderer for a given camera
  24567. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  24568. */
  24569. Scene.prototype.disableDepthRenderer = function (camera) {
  24570. camera = camera || this.activeCamera;
  24571. if (!camera || !this._depthRenderer[camera.id]) {
  24572. return;
  24573. }
  24574. this._depthRenderer[camera.id].dispose();
  24575. delete this._depthRenderer[camera.id];
  24576. };
  24577. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  24578. if (ratio === void 0) { ratio = 1; }
  24579. if (this._geometryBufferRenderer) {
  24580. return this._geometryBufferRenderer;
  24581. }
  24582. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  24583. if (!this._geometryBufferRenderer.isSupported) {
  24584. this._geometryBufferRenderer = null;
  24585. }
  24586. return this._geometryBufferRenderer;
  24587. };
  24588. Scene.prototype.disableGeometryBufferRenderer = function () {
  24589. if (!this._geometryBufferRenderer) {
  24590. return;
  24591. }
  24592. this._geometryBufferRenderer.dispose();
  24593. this._geometryBufferRenderer = null;
  24594. };
  24595. Scene.prototype.freezeMaterials = function () {
  24596. for (var i = 0; i < this.materials.length; i++) {
  24597. this.materials[i].freeze();
  24598. }
  24599. };
  24600. Scene.prototype.unfreezeMaterials = function () {
  24601. for (var i = 0; i < this.materials.length; i++) {
  24602. this.materials[i].unfreeze();
  24603. }
  24604. };
  24605. Scene.prototype.dispose = function () {
  24606. this.beforeRender = null;
  24607. this.afterRender = null;
  24608. this.skeletons = [];
  24609. this.morphTargetManagers = [];
  24610. this.importedMeshesFiles = new Array();
  24611. this.stopAllAnimations();
  24612. this.resetCachedMaterial();
  24613. for (var key in this._depthRenderer) {
  24614. this._depthRenderer[key].dispose();
  24615. }
  24616. if (this._gamepadManager) {
  24617. this._gamepadManager.dispose();
  24618. this._gamepadManager = null;
  24619. }
  24620. // Smart arrays
  24621. if (this.activeCamera) {
  24622. this.activeCamera._activeMeshes.dispose();
  24623. this.activeCamera = null;
  24624. }
  24625. this._activeMeshes.dispose();
  24626. this._renderingManager.dispose();
  24627. this._processedMaterials.dispose();
  24628. this._activeParticleSystems.dispose();
  24629. this._activeSkeletons.dispose();
  24630. this._softwareSkinnedMeshes.dispose();
  24631. this._renderTargets.dispose();
  24632. if (this._boundingBoxRenderer) {
  24633. this._boundingBoxRenderer.dispose();
  24634. }
  24635. this._meshesForIntersections.dispose();
  24636. this._toBeDisposed.dispose();
  24637. // Abort active requests
  24638. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  24639. var request = _a[_i];
  24640. request.abort();
  24641. }
  24642. // Debug layer
  24643. if (this._debugLayer) {
  24644. this._debugLayer.hide();
  24645. }
  24646. // Events
  24647. this.onDisposeObservable.notifyObservers(this);
  24648. this.onDisposeObservable.clear();
  24649. this.onBeforeRenderObservable.clear();
  24650. this.onAfterRenderObservable.clear();
  24651. this.OnBeforeRenderTargetsRenderObservable.clear();
  24652. this.OnAfterRenderTargetsRenderObservable.clear();
  24653. this.onAfterStepObservable.clear();
  24654. this.onBeforeStepObservable.clear();
  24655. this.onBeforeActiveMeshesEvaluationObservable.clear();
  24656. this.onAfterActiveMeshesEvaluationObservable.clear();
  24657. this.onBeforeParticlesRenderingObservable.clear();
  24658. this.onAfterParticlesRenderingObservable.clear();
  24659. this.onBeforeSpritesRenderingObservable.clear();
  24660. this.onAfterSpritesRenderingObservable.clear();
  24661. this.onBeforeDrawPhaseObservable.clear();
  24662. this.onAfterDrawPhaseObservable.clear();
  24663. this.onBeforePhysicsObservable.clear();
  24664. this.onAfterPhysicsObservable.clear();
  24665. this.onBeforeAnimationsObservable.clear();
  24666. this.onAfterAnimationsObservable.clear();
  24667. this.onDataLoadedObservable.clear();
  24668. this.detachControl();
  24669. // Release sounds & sounds tracks
  24670. if (BABYLON.AudioEngine) {
  24671. this.disposeSounds();
  24672. }
  24673. // VR Helper
  24674. if (this.VRHelper) {
  24675. this.VRHelper.dispose();
  24676. }
  24677. // Detach cameras
  24678. var canvas = this._engine.getRenderingCanvas();
  24679. if (canvas) {
  24680. var index;
  24681. for (index = 0; index < this.cameras.length; index++) {
  24682. this.cameras[index].detachControl(canvas);
  24683. }
  24684. }
  24685. // Release animation groups
  24686. while (this.animationGroups.length) {
  24687. this.animationGroups[0].dispose();
  24688. }
  24689. // Release lights
  24690. while (this.lights.length) {
  24691. this.lights[0].dispose();
  24692. }
  24693. // Release meshes
  24694. while (this.meshes.length) {
  24695. this.meshes[0].dispose(true);
  24696. }
  24697. while (this.transformNodes.length) {
  24698. this.removeTransformNode(this.transformNodes[0]);
  24699. }
  24700. // Release cameras
  24701. while (this.cameras.length) {
  24702. this.cameras[0].dispose();
  24703. }
  24704. // Release materials
  24705. if (this.defaultMaterial) {
  24706. this.defaultMaterial.dispose();
  24707. }
  24708. while (this.multiMaterials.length) {
  24709. this.multiMaterials[0].dispose();
  24710. }
  24711. while (this.materials.length) {
  24712. this.materials[0].dispose();
  24713. }
  24714. // Release particles
  24715. while (this.particleSystems.length) {
  24716. this.particleSystems[0].dispose();
  24717. }
  24718. // Release sprites
  24719. while (this.spriteManagers.length) {
  24720. this.spriteManagers[0].dispose();
  24721. }
  24722. // Release postProcesses
  24723. while (this.postProcesses.length) {
  24724. this.postProcesses[0].dispose();
  24725. }
  24726. // Release layers
  24727. while (this.layers.length) {
  24728. this.layers[0].dispose();
  24729. }
  24730. while (this.effectLayers.length) {
  24731. this.effectLayers[0].dispose();
  24732. }
  24733. // Release textures
  24734. while (this.textures.length) {
  24735. this.textures[0].dispose();
  24736. }
  24737. // Release UBO
  24738. this._sceneUbo.dispose();
  24739. if (this._alternateSceneUbo) {
  24740. this._alternateSceneUbo.dispose();
  24741. }
  24742. // Post-processes
  24743. this.postProcessManager.dispose();
  24744. if (this._postProcessRenderPipelineManager) {
  24745. this._postProcessRenderPipelineManager.dispose();
  24746. }
  24747. // Physics
  24748. if (this._physicsEngine) {
  24749. this.disablePhysicsEngine();
  24750. }
  24751. // Remove from engine
  24752. index = this._engine.scenes.indexOf(this);
  24753. if (index > -1) {
  24754. this._engine.scenes.splice(index, 1);
  24755. }
  24756. this._engine.wipeCaches(true);
  24757. this._isDisposed = true;
  24758. };
  24759. Object.defineProperty(Scene.prototype, "isDisposed", {
  24760. get: function () {
  24761. return this._isDisposed;
  24762. },
  24763. enumerable: true,
  24764. configurable: true
  24765. });
  24766. // Release sounds & sounds tracks
  24767. Scene.prototype.disposeSounds = function () {
  24768. if (!this._mainSoundTrack) {
  24769. return;
  24770. }
  24771. this.mainSoundTrack.dispose();
  24772. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  24773. this.soundTracks[scIndex].dispose();
  24774. }
  24775. };
  24776. // Octrees
  24777. /**
  24778. * Get the world extend vectors with an optional filter
  24779. *
  24780. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  24781. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  24782. */
  24783. Scene.prototype.getWorldExtends = function (filterPredicate) {
  24784. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  24785. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  24786. filterPredicate = filterPredicate || (function () { return true; });
  24787. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  24788. mesh.computeWorldMatrix(true);
  24789. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  24790. return;
  24791. }
  24792. var boundingInfo = mesh.getBoundingInfo();
  24793. var minBox = boundingInfo.boundingBox.minimumWorld;
  24794. var maxBox = boundingInfo.boundingBox.maximumWorld;
  24795. BABYLON.Tools.CheckExtends(minBox, min, max);
  24796. BABYLON.Tools.CheckExtends(maxBox, min, max);
  24797. });
  24798. return {
  24799. min: min,
  24800. max: max
  24801. };
  24802. };
  24803. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  24804. if (maxCapacity === void 0) { maxCapacity = 64; }
  24805. if (maxDepth === void 0) { maxDepth = 2; }
  24806. if (!this._selectionOctree) {
  24807. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  24808. }
  24809. var worldExtends = this.getWorldExtends();
  24810. // Update octree
  24811. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  24812. return this._selectionOctree;
  24813. };
  24814. // Picking
  24815. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  24816. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24817. var result = BABYLON.Ray.Zero();
  24818. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  24819. return result;
  24820. };
  24821. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  24822. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24823. var engine = this._engine;
  24824. if (!camera) {
  24825. if (!this.activeCamera)
  24826. throw new Error("Active camera not set");
  24827. camera = this.activeCamera;
  24828. }
  24829. var cameraViewport = camera.viewport;
  24830. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24831. // Moving coordinates to local viewport world
  24832. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24833. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24834. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  24835. return this;
  24836. };
  24837. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  24838. var result = BABYLON.Ray.Zero();
  24839. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  24840. return result;
  24841. };
  24842. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  24843. if (!BABYLON.PickingInfo) {
  24844. return this;
  24845. }
  24846. var engine = this._engine;
  24847. if (!camera) {
  24848. if (!this.activeCamera)
  24849. throw new Error("Active camera not set");
  24850. camera = this.activeCamera;
  24851. }
  24852. var cameraViewport = camera.viewport;
  24853. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24854. var identity = BABYLON.Matrix.Identity();
  24855. // Moving coordinates to local viewport world
  24856. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24857. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24858. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  24859. return this;
  24860. };
  24861. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  24862. if (!BABYLON.PickingInfo) {
  24863. return null;
  24864. }
  24865. var pickingInfo = null;
  24866. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24867. var mesh = this.meshes[meshIndex];
  24868. if (predicate) {
  24869. if (!predicate(mesh)) {
  24870. continue;
  24871. }
  24872. }
  24873. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24874. continue;
  24875. }
  24876. var world = mesh.getWorldMatrix();
  24877. var ray = rayFunction(world);
  24878. var result = mesh.intersects(ray, fastCheck);
  24879. if (!result || !result.hit)
  24880. continue;
  24881. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24882. continue;
  24883. pickingInfo = result;
  24884. if (fastCheck) {
  24885. break;
  24886. }
  24887. }
  24888. return pickingInfo || new BABYLON.PickingInfo();
  24889. };
  24890. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  24891. if (!BABYLON.PickingInfo) {
  24892. return null;
  24893. }
  24894. var pickingInfos = new Array();
  24895. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24896. var mesh = this.meshes[meshIndex];
  24897. if (predicate) {
  24898. if (!predicate(mesh)) {
  24899. continue;
  24900. }
  24901. }
  24902. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24903. continue;
  24904. }
  24905. var world = mesh.getWorldMatrix();
  24906. var ray = rayFunction(world);
  24907. var result = mesh.intersects(ray, false);
  24908. if (!result || !result.hit)
  24909. continue;
  24910. pickingInfos.push(result);
  24911. }
  24912. return pickingInfos;
  24913. };
  24914. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  24915. if (!BABYLON.PickingInfo) {
  24916. return null;
  24917. }
  24918. var pickingInfo = null;
  24919. if (!camera) {
  24920. if (!this.activeCamera) {
  24921. return null;
  24922. }
  24923. camera = this.activeCamera;
  24924. }
  24925. if (this.spriteManagers.length > 0) {
  24926. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  24927. var spriteManager = this.spriteManagers[spriteIndex];
  24928. if (!spriteManager.isPickable) {
  24929. continue;
  24930. }
  24931. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  24932. if (!result || !result.hit)
  24933. continue;
  24934. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24935. continue;
  24936. pickingInfo = result;
  24937. if (fastCheck) {
  24938. break;
  24939. }
  24940. }
  24941. }
  24942. return pickingInfo || new BABYLON.PickingInfo();
  24943. };
  24944. /** Launch a ray to try to pick a mesh in the scene
  24945. * @param x position on screen
  24946. * @param y position on screen
  24947. * @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
  24948. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24949. * @param 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.pick = function (x, y, predicate, fastCheck, camera) {
  24952. var _this = this;
  24953. if (!BABYLON.PickingInfo) {
  24954. return null;
  24955. }
  24956. return this._internalPick(function (world) {
  24957. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  24958. return _this._tempPickingRay;
  24959. }, predicate, fastCheck);
  24960. };
  24961. /** Launch a ray to try to pick a sprite in the scene
  24962. * @param x position on screen
  24963. * @param y position on screen
  24964. * @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
  24965. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24966. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24967. */
  24968. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  24969. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  24970. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  24971. };
  24972. /** Use the given ray to pick a mesh in the scene
  24973. * @param ray The ray to use to pick meshes
  24974. * @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
  24975. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24976. */
  24977. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  24978. var _this = this;
  24979. return this._internalPick(function (world) {
  24980. if (!_this._pickWithRayInverseMatrix) {
  24981. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24982. }
  24983. world.invertToRef(_this._pickWithRayInverseMatrix);
  24984. if (!_this._cachedRayForTransform) {
  24985. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24986. }
  24987. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24988. return _this._cachedRayForTransform;
  24989. }, predicate, fastCheck);
  24990. };
  24991. /**
  24992. * Launch a ray to try to pick a mesh in the scene
  24993. * @param x X position on screen
  24994. * @param y Y position on screen
  24995. * @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
  24996. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24997. */
  24998. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  24999. var _this = this;
  25000. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  25001. };
  25002. /**
  25003. * Launch a ray to try to pick a mesh in the scene
  25004. * @param ray Ray to use
  25005. * @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
  25006. */
  25007. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  25008. var _this = this;
  25009. return this._internalMultiPick(function (world) {
  25010. if (!_this._pickWithRayInverseMatrix) {
  25011. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25012. }
  25013. world.invertToRef(_this._pickWithRayInverseMatrix);
  25014. if (!_this._cachedRayForTransform) {
  25015. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25016. }
  25017. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25018. return _this._cachedRayForTransform;
  25019. }, predicate);
  25020. };
  25021. Scene.prototype.setPointerOverMesh = function (mesh) {
  25022. if (this._pointerOverMesh === mesh) {
  25023. return;
  25024. }
  25025. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25026. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25027. }
  25028. this._pointerOverMesh = mesh;
  25029. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25030. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25031. }
  25032. };
  25033. Scene.prototype.getPointerOverMesh = function () {
  25034. return this._pointerOverMesh;
  25035. };
  25036. Scene.prototype.setPointerOverSprite = function (sprite) {
  25037. if (this._pointerOverSprite === sprite) {
  25038. return;
  25039. }
  25040. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25041. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25042. }
  25043. this._pointerOverSprite = sprite;
  25044. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25045. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25046. }
  25047. };
  25048. Scene.prototype.getPointerOverSprite = function () {
  25049. return this._pointerOverSprite;
  25050. };
  25051. // Physics
  25052. Scene.prototype.getPhysicsEngine = function () {
  25053. return this._physicsEngine;
  25054. };
  25055. /**
  25056. * Enables physics to the current scene
  25057. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  25058. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  25059. * @return {boolean} was the physics engine initialized
  25060. */
  25061. Scene.prototype.enablePhysics = function (gravity, plugin) {
  25062. if (gravity === void 0) { gravity = null; }
  25063. if (this._physicsEngine) {
  25064. return true;
  25065. }
  25066. try {
  25067. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  25068. return true;
  25069. }
  25070. catch (e) {
  25071. BABYLON.Tools.Error(e.message);
  25072. return false;
  25073. }
  25074. };
  25075. Scene.prototype.disablePhysicsEngine = function () {
  25076. if (!this._physicsEngine) {
  25077. return;
  25078. }
  25079. this._physicsEngine.dispose();
  25080. this._physicsEngine = null;
  25081. };
  25082. Scene.prototype.isPhysicsEnabled = function () {
  25083. return this._physicsEngine !== undefined;
  25084. };
  25085. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25086. var mesh = compound.parts[0].mesh;
  25087. if (mesh.physicsImpostor) {
  25088. mesh.physicsImpostor.dispose();
  25089. mesh.physicsImpostor = null;
  25090. }
  25091. };
  25092. // Misc.
  25093. Scene.prototype._rebuildGeometries = function () {
  25094. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25095. var geometry = _a[_i];
  25096. geometry._rebuild();
  25097. }
  25098. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25099. var mesh = _c[_b];
  25100. mesh._rebuild();
  25101. }
  25102. if (this.postProcessManager) {
  25103. this.postProcessManager._rebuild();
  25104. }
  25105. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25106. var layer = _e[_d];
  25107. layer._rebuild();
  25108. }
  25109. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25110. var effectLayer = _g[_f];
  25111. effectLayer._rebuild();
  25112. }
  25113. if (this._boundingBoxRenderer) {
  25114. this._boundingBoxRenderer._rebuild();
  25115. }
  25116. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25117. var system = _j[_h];
  25118. system.rebuild();
  25119. }
  25120. if (this._postProcessRenderPipelineManager) {
  25121. this._postProcessRenderPipelineManager._rebuild();
  25122. }
  25123. };
  25124. Scene.prototype._rebuildTextures = function () {
  25125. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25126. var texture = _a[_i];
  25127. texture._rebuild();
  25128. }
  25129. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25130. };
  25131. /**
  25132. * Creates a default light for the scene.
  25133. * @param replace Whether to replace the existing lights in the scene.
  25134. */
  25135. Scene.prototype.createDefaultLight = function (replace) {
  25136. if (replace === void 0) { replace = false; }
  25137. // Dispose existing light in replace mode.
  25138. if (replace) {
  25139. if (this.lights) {
  25140. for (var i = 0; i < this.lights.length; i++) {
  25141. this.lights[i].dispose();
  25142. }
  25143. }
  25144. }
  25145. // Light
  25146. if (this.lights.length === 0) {
  25147. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25148. }
  25149. };
  25150. /**
  25151. * Creates a default camera for the scene.
  25152. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25153. * @param replace Whether to replace the existing active camera in the scene.
  25154. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25155. */
  25156. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25157. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25158. if (replace === void 0) { replace = false; }
  25159. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25160. // Dispose existing camera in replace mode.
  25161. if (replace) {
  25162. if (this.activeCamera) {
  25163. this.activeCamera.dispose();
  25164. this.activeCamera = null;
  25165. }
  25166. }
  25167. // Camera
  25168. if (!this.activeCamera) {
  25169. var worldExtends = this.getWorldExtends();
  25170. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25171. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25172. var camera;
  25173. var radius = worldSize.length() * 1.5;
  25174. // empty scene scenario!
  25175. if (!isFinite(radius)) {
  25176. radius = 1;
  25177. worldCenter.copyFromFloats(0, 0, 0);
  25178. }
  25179. if (createArcRotateCamera) {
  25180. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25181. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25182. arcRotateCamera.wheelPrecision = 100 / radius;
  25183. camera = arcRotateCamera;
  25184. }
  25185. else {
  25186. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25187. freeCamera.setTarget(worldCenter);
  25188. camera = freeCamera;
  25189. }
  25190. camera.minZ = radius * 0.01;
  25191. camera.maxZ = radius * 1000;
  25192. camera.speed = radius * 0.2;
  25193. this.activeCamera = camera;
  25194. var canvas = this.getEngine().getRenderingCanvas();
  25195. if (attachCameraControls && canvas) {
  25196. camera.attachControl(canvas);
  25197. }
  25198. }
  25199. };
  25200. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25201. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25202. if (replace === void 0) { replace = false; }
  25203. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25204. this.createDefaultLight(replace);
  25205. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25206. };
  25207. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25208. if (pbr === void 0) { pbr = false; }
  25209. if (scale === void 0) { scale = 1000; }
  25210. if (blur === void 0) { blur = 0; }
  25211. if (environmentTexture) {
  25212. this.environmentTexture = environmentTexture;
  25213. }
  25214. if (!this.environmentTexture) {
  25215. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25216. return null;
  25217. }
  25218. // Skybox
  25219. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25220. if (pbr) {
  25221. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25222. hdrSkyboxMaterial.backFaceCulling = false;
  25223. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25224. if (hdrSkyboxMaterial.reflectionTexture) {
  25225. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25226. }
  25227. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25228. hdrSkyboxMaterial.disableLighting = true;
  25229. hdrSkyboxMaterial.twoSidedLighting = true;
  25230. hdrSkybox.infiniteDistance = true;
  25231. hdrSkybox.material = hdrSkyboxMaterial;
  25232. }
  25233. else {
  25234. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25235. skyboxMaterial.backFaceCulling = false;
  25236. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25237. if (skyboxMaterial.reflectionTexture) {
  25238. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25239. }
  25240. skyboxMaterial.disableLighting = true;
  25241. hdrSkybox.infiniteDistance = true;
  25242. hdrSkybox.material = skyboxMaterial;
  25243. }
  25244. return hdrSkybox;
  25245. };
  25246. Scene.prototype.createDefaultEnvironment = function (options) {
  25247. if (BABYLON.EnvironmentHelper) {
  25248. return new BABYLON.EnvironmentHelper(options, this);
  25249. }
  25250. return null;
  25251. };
  25252. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25253. if (webVROptions === void 0) { webVROptions = {}; }
  25254. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25255. };
  25256. // Tags
  25257. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25258. if (tagsQuery === undefined) {
  25259. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25260. return list;
  25261. }
  25262. var listByTags = [];
  25263. forEach = forEach || (function (item) { return; });
  25264. for (var i in list) {
  25265. var item = list[i];
  25266. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25267. listByTags.push(item);
  25268. forEach(item);
  25269. }
  25270. }
  25271. return listByTags;
  25272. };
  25273. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25274. return this._getByTags(this.meshes, tagsQuery, forEach);
  25275. };
  25276. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25277. return this._getByTags(this.cameras, tagsQuery, forEach);
  25278. };
  25279. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25280. return this._getByTags(this.lights, tagsQuery, forEach);
  25281. };
  25282. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25283. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25284. };
  25285. /**
  25286. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25287. * This allowed control for front to back rendering or reversly depending of the special needs.
  25288. *
  25289. * @param renderingGroupId The rendering group id corresponding to its index
  25290. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25291. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25292. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25293. */
  25294. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25295. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25296. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25297. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25298. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25299. };
  25300. /**
  25301. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25302. *
  25303. * @param renderingGroupId The rendering group id corresponding to its index
  25304. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25305. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25306. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25307. */
  25308. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25309. if (depth === void 0) { depth = true; }
  25310. if (stencil === void 0) { stencil = true; }
  25311. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25312. };
  25313. /**
  25314. * Will flag all materials as dirty to trigger new shader compilation
  25315. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25316. */
  25317. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25318. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25319. var material = _a[_i];
  25320. if (predicate && !predicate(material)) {
  25321. continue;
  25322. }
  25323. material.markAsDirty(flag);
  25324. }
  25325. };
  25326. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25327. var _this = this;
  25328. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25329. this._activeRequests.push(request);
  25330. request.onCompleteObservable.add(function (request) {
  25331. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25332. });
  25333. return request;
  25334. };
  25335. /** @ignore */
  25336. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25337. var _this = this;
  25338. return new Promise(function (resolve, reject) {
  25339. _this._loadFile(url, function (data) {
  25340. resolve(data);
  25341. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25342. reject(exception);
  25343. });
  25344. });
  25345. };
  25346. // Statics
  25347. Scene._FOGMODE_NONE = 0;
  25348. Scene._FOGMODE_EXP = 1;
  25349. Scene._FOGMODE_EXP2 = 2;
  25350. Scene._FOGMODE_LINEAR = 3;
  25351. Scene._uniqueIdCounter = 0;
  25352. Scene.MinDeltaTime = 1.0;
  25353. Scene.MaxDeltaTime = 1000.0;
  25354. /** The distance in pixel that you have to move to prevent some events */
  25355. Scene.DragMovementThreshold = 10; // in pixels
  25356. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25357. Scene.LongPressDelay = 500; // in milliseconds
  25358. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25359. Scene.DoubleClickDelay = 300; // in milliseconds
  25360. /** If you need to check double click without raising a single click at first click, enable this flag */
  25361. Scene.ExclusiveDoubleClickMode = false;
  25362. return Scene;
  25363. }());
  25364. BABYLON.Scene = Scene;
  25365. })(BABYLON || (BABYLON = {}));
  25366. //# sourceMappingURL=babylon.scene.js.map
  25367. var BABYLON;
  25368. (function (BABYLON) {
  25369. /**
  25370. * Set of assets to keep when moving a scene into an asset container.
  25371. */
  25372. var KeepAssets = /** @class */ (function () {
  25373. function KeepAssets() {
  25374. /**
  25375. * Cameras to keep.
  25376. */
  25377. this.cameras = new Array();
  25378. /**
  25379. * Lights to keep.
  25380. */
  25381. this.lights = new Array();
  25382. /**
  25383. * Meshes to keep.
  25384. */
  25385. this.meshes = new Array();
  25386. /**
  25387. * Skeletons to keep.
  25388. */
  25389. this.skeletons = new Array();
  25390. /**
  25391. * ParticleSystems to keep.
  25392. */
  25393. this.particleSystems = new Array();
  25394. /**
  25395. * Animations to keep.
  25396. */
  25397. this.animations = new Array();
  25398. /**
  25399. * MultiMaterials to keep.
  25400. */
  25401. this.multiMaterials = new Array();
  25402. /**
  25403. * Materials to keep.
  25404. */
  25405. this.materials = new Array();
  25406. /**
  25407. * MorphTargetManagers to keep.
  25408. */
  25409. this.morphTargetManagers = new Array();
  25410. /**
  25411. * Geometries to keep.
  25412. */
  25413. this.geometries = new Array();
  25414. /**
  25415. * TransformNodes to keep.
  25416. */
  25417. this.transformNodes = new Array();
  25418. /**
  25419. * LensFlareSystems to keep.
  25420. */
  25421. this.lensFlareSystems = new Array();
  25422. /**
  25423. * ShadowGenerators to keep.
  25424. */
  25425. this.shadowGenerators = new Array();
  25426. /**
  25427. * ActionManagers to keep.
  25428. */
  25429. this.actionManagers = new Array();
  25430. /**
  25431. * Sounds to keep.
  25432. */
  25433. this.sounds = new Array();
  25434. }
  25435. return KeepAssets;
  25436. }());
  25437. BABYLON.KeepAssets = KeepAssets;
  25438. /**
  25439. * Container with a set of assets that can be added or removed from a scene.
  25440. */
  25441. var AssetContainer = /** @class */ (function () {
  25442. /**
  25443. * Instantiates an AssetContainer.
  25444. * @param scene The scene the AssetContainer belongs to.
  25445. */
  25446. function AssetContainer(scene) {
  25447. // Objects
  25448. /**
  25449. * Cameras populated in the container.
  25450. */
  25451. this.cameras = new Array();
  25452. /**
  25453. * Lights populated in the container.
  25454. */
  25455. this.lights = new Array();
  25456. /**
  25457. * Meshes populated in the container.
  25458. */
  25459. this.meshes = new Array();
  25460. /**
  25461. * Skeletons populated in the container.
  25462. */
  25463. this.skeletons = new Array();
  25464. /**
  25465. * ParticleSystems populated in the container.
  25466. */
  25467. this.particleSystems = new Array();
  25468. /**
  25469. * Animations populated in the container.
  25470. */
  25471. this.animations = new Array();
  25472. /**
  25473. * MultiMaterials populated in the container.
  25474. */
  25475. this.multiMaterials = new Array();
  25476. /**
  25477. * Materials populated in the container.
  25478. */
  25479. this.materials = new Array();
  25480. /**
  25481. * MorphTargetManagers populated in the container.
  25482. */
  25483. this.morphTargetManagers = new Array();
  25484. /**
  25485. * Geometries populated in the container.
  25486. */
  25487. this.geometries = new Array();
  25488. /**
  25489. * TransformNodes populated in the container.
  25490. */
  25491. this.transformNodes = new Array();
  25492. /**
  25493. * LensFlareSystems populated in the container.
  25494. */
  25495. this.lensFlareSystems = new Array();
  25496. /**
  25497. * ShadowGenerators populated in the container.
  25498. */
  25499. this.shadowGenerators = new Array();
  25500. /**
  25501. * ActionManagers populated in the container.
  25502. */
  25503. this.actionManagers = new Array();
  25504. /**
  25505. * Sounds populated in the container.
  25506. */
  25507. this.sounds = new Array();
  25508. this.scene = scene;
  25509. }
  25510. /**
  25511. * Adds all the assets from the container to the scene.
  25512. */
  25513. AssetContainer.prototype.addAllToScene = function () {
  25514. var _this = this;
  25515. this.cameras.forEach(function (o) {
  25516. _this.scene.addCamera(o);
  25517. });
  25518. this.lights.forEach(function (o) {
  25519. _this.scene.addLight(o);
  25520. });
  25521. this.meshes.forEach(function (o) {
  25522. _this.scene.addMesh(o);
  25523. });
  25524. this.skeletons.forEach(function (o) {
  25525. _this.scene.addSkeleton(o);
  25526. });
  25527. this.particleSystems.forEach(function (o) {
  25528. _this.scene.addParticleSystem(o);
  25529. });
  25530. this.animations.forEach(function (o) {
  25531. _this.scene.addAnimation(o);
  25532. });
  25533. this.multiMaterials.forEach(function (o) {
  25534. _this.scene.addMultiMaterial(o);
  25535. });
  25536. this.materials.forEach(function (o) {
  25537. _this.scene.addMaterial(o);
  25538. });
  25539. this.morphTargetManagers.forEach(function (o) {
  25540. _this.scene.addMorphTargetManager(o);
  25541. });
  25542. this.geometries.forEach(function (o) {
  25543. _this.scene.addGeometry(o);
  25544. });
  25545. this.transformNodes.forEach(function (o) {
  25546. _this.scene.addTransformNode(o);
  25547. });
  25548. this.lensFlareSystems.forEach(function (o) {
  25549. _this.scene.addLensFlareSystem(o);
  25550. });
  25551. this.actionManagers.forEach(function (o) {
  25552. _this.scene.addActionManager(o);
  25553. });
  25554. this.sounds.forEach(function (o) {
  25555. o.play();
  25556. o.autoplay = true;
  25557. _this.scene.mainSoundTrack.AddSound(o);
  25558. });
  25559. };
  25560. /**
  25561. * Removes all the assets in the container from the scene
  25562. */
  25563. AssetContainer.prototype.removeAllFromScene = function () {
  25564. var _this = this;
  25565. this.cameras.forEach(function (o) {
  25566. _this.scene.removeCamera(o);
  25567. });
  25568. this.lights.forEach(function (o) {
  25569. _this.scene.removeLight(o);
  25570. });
  25571. this.meshes.forEach(function (o) {
  25572. _this.scene.removeMesh(o);
  25573. });
  25574. this.skeletons.forEach(function (o) {
  25575. _this.scene.removeSkeleton(o);
  25576. });
  25577. this.particleSystems.forEach(function (o) {
  25578. _this.scene.removeParticleSystem(o);
  25579. });
  25580. this.animations.forEach(function (o) {
  25581. _this.scene.removeAnimation(o);
  25582. });
  25583. this.multiMaterials.forEach(function (o) {
  25584. _this.scene.removeMultiMaterial(o);
  25585. });
  25586. this.materials.forEach(function (o) {
  25587. _this.scene.removeMaterial(o);
  25588. });
  25589. this.morphTargetManagers.forEach(function (o) {
  25590. _this.scene.removeMorphTargetManager(o);
  25591. });
  25592. this.geometries.forEach(function (o) {
  25593. _this.scene.removeGeometry(o);
  25594. });
  25595. this.transformNodes.forEach(function (o) {
  25596. _this.scene.removeTransformNode(o);
  25597. });
  25598. this.lensFlareSystems.forEach(function (o) {
  25599. _this.scene.removeLensFlareSystem(o);
  25600. });
  25601. this.actionManagers.forEach(function (o) {
  25602. _this.scene.removeActionManager(o);
  25603. });
  25604. this.sounds.forEach(function (o) {
  25605. o.stop();
  25606. o.autoplay = false;
  25607. _this.scene.mainSoundTrack.RemoveSound(o);
  25608. });
  25609. };
  25610. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  25611. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  25612. var asset = sourceAssets_1[_i];
  25613. var move = true;
  25614. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  25615. var keepAsset = keepAssets_1[_a];
  25616. if (asset === keepAsset) {
  25617. move = false;
  25618. break;
  25619. }
  25620. }
  25621. if (move) {
  25622. targetAssets.push(asset);
  25623. }
  25624. }
  25625. };
  25626. /**
  25627. * Removes all the assets contained in the scene and adds them to the container.
  25628. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  25629. */
  25630. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  25631. if (keepAssets === undefined) {
  25632. keepAssets = new KeepAssets();
  25633. }
  25634. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  25635. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  25636. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  25637. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  25638. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  25639. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  25640. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  25641. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  25642. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  25643. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  25644. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  25645. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  25646. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  25647. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  25648. this.removeAllFromScene();
  25649. };
  25650. return AssetContainer;
  25651. }());
  25652. BABYLON.AssetContainer = AssetContainer;
  25653. })(BABYLON || (BABYLON = {}));
  25654. //# sourceMappingURL=babylon.assetContainer.js.map
  25655. var BABYLON;
  25656. (function (BABYLON) {
  25657. var Buffer = /** @class */ (function () {
  25658. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  25659. if (instanced === void 0) { instanced = false; }
  25660. if (engine instanceof BABYLON.Mesh) {
  25661. this._engine = engine.getScene().getEngine();
  25662. }
  25663. else {
  25664. this._engine = engine;
  25665. }
  25666. this._updatable = updatable;
  25667. this._instanced = instanced;
  25668. this._data = data;
  25669. this._strideSize = stride;
  25670. if (!postponeInternalCreation) {
  25671. this.create();
  25672. }
  25673. }
  25674. /**
  25675. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  25676. * @param kind defines the vertex buffer kind (position, normal, etc.)
  25677. * @param offset defines offset in the buffer (0 by default)
  25678. * @param size defines the size in floats of attributes (position is 3 for instance)
  25679. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  25680. * @param instanced defines if the vertex buffer contains indexed data
  25681. * @returns the new vertex buffer
  25682. */
  25683. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  25684. // a lot of these parameters are ignored as they are overriden by the buffer
  25685. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  25686. };
  25687. // Properties
  25688. Buffer.prototype.isUpdatable = function () {
  25689. return this._updatable;
  25690. };
  25691. Buffer.prototype.getData = function () {
  25692. return this._data;
  25693. };
  25694. Buffer.prototype.getBuffer = function () {
  25695. return this._buffer;
  25696. };
  25697. Buffer.prototype.getStrideSize = function () {
  25698. return this._strideSize;
  25699. };
  25700. // public getIsInstanced(): boolean {
  25701. // return this._instanced;
  25702. // }
  25703. // public get instanceDivisor(): number {
  25704. // return this._instanceDivisor;
  25705. // }
  25706. // public set instanceDivisor(value: number) {
  25707. // this._instanceDivisor = value;
  25708. // if (value == 0) {
  25709. // this._instanced = false;
  25710. // } else {
  25711. // this._instanced = true;
  25712. // }
  25713. // }
  25714. // Methods
  25715. Buffer.prototype.create = function (data) {
  25716. if (data === void 0) { data = null; }
  25717. if (!data && this._buffer) {
  25718. return; // nothing to do
  25719. }
  25720. data = data || this._data;
  25721. if (!data) {
  25722. return;
  25723. }
  25724. if (!this._buffer) {
  25725. if (this._updatable) {
  25726. this._buffer = this._engine.createDynamicVertexBuffer(data);
  25727. this._data = data;
  25728. }
  25729. else {
  25730. this._buffer = this._engine.createVertexBuffer(data);
  25731. }
  25732. }
  25733. else if (this._updatable) {
  25734. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  25735. this._data = data;
  25736. }
  25737. };
  25738. Buffer.prototype._rebuild = function () {
  25739. this._buffer = null;
  25740. this.create(this._data);
  25741. };
  25742. Buffer.prototype.update = function (data) {
  25743. this.create(data);
  25744. };
  25745. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  25746. if (!this._buffer) {
  25747. return;
  25748. }
  25749. if (this._updatable) {
  25750. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  25751. this._data = null;
  25752. }
  25753. };
  25754. Buffer.prototype.dispose = function () {
  25755. if (!this._buffer) {
  25756. return;
  25757. }
  25758. if (this._engine._releaseBuffer(this._buffer)) {
  25759. this._buffer = null;
  25760. }
  25761. };
  25762. return Buffer;
  25763. }());
  25764. BABYLON.Buffer = Buffer;
  25765. })(BABYLON || (BABYLON = {}));
  25766. //# sourceMappingURL=babylon.buffer.js.map
  25767. var BABYLON;
  25768. (function (BABYLON) {
  25769. var VertexBuffer = /** @class */ (function () {
  25770. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  25771. if (data instanceof BABYLON.Buffer) {
  25772. if (!stride) {
  25773. stride = data.getStrideSize();
  25774. }
  25775. this._buffer = data;
  25776. this._ownsBuffer = false;
  25777. }
  25778. else {
  25779. if (!stride) {
  25780. stride = VertexBuffer.DeduceStride(kind);
  25781. }
  25782. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  25783. this._ownsBuffer = true;
  25784. }
  25785. this._stride = stride;
  25786. this._instanced = instanced !== undefined ? instanced : false;
  25787. this._instanceDivisor = instanced ? 1 : 0;
  25788. this._offset = offset ? offset : 0;
  25789. this._size = size ? size : stride;
  25790. this._kind = kind;
  25791. }
  25792. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  25793. /**
  25794. * Gets or sets the instance divisor when in instanced mode
  25795. */
  25796. get: function () {
  25797. return this._instanceDivisor;
  25798. },
  25799. set: function (value) {
  25800. this._instanceDivisor = value;
  25801. if (value == 0) {
  25802. this._instanced = false;
  25803. }
  25804. else {
  25805. this._instanced = true;
  25806. }
  25807. },
  25808. enumerable: true,
  25809. configurable: true
  25810. });
  25811. VertexBuffer.prototype._rebuild = function () {
  25812. if (!this._buffer) {
  25813. return;
  25814. }
  25815. this._buffer._rebuild();
  25816. };
  25817. /**
  25818. * Returns the kind of the VertexBuffer (string).
  25819. */
  25820. VertexBuffer.prototype.getKind = function () {
  25821. return this._kind;
  25822. };
  25823. // Properties
  25824. /**
  25825. * Boolean : is the VertexBuffer updatable ?
  25826. */
  25827. VertexBuffer.prototype.isUpdatable = function () {
  25828. return this._buffer.isUpdatable();
  25829. };
  25830. /**
  25831. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  25832. */
  25833. VertexBuffer.prototype.getData = function () {
  25834. return this._buffer.getData();
  25835. };
  25836. /**
  25837. * Returns the WebGLBuffer associated to the VertexBuffer.
  25838. */
  25839. VertexBuffer.prototype.getBuffer = function () {
  25840. return this._buffer.getBuffer();
  25841. };
  25842. /**
  25843. * Returns the stride of the VertexBuffer (integer).
  25844. */
  25845. VertexBuffer.prototype.getStrideSize = function () {
  25846. return this._stride;
  25847. };
  25848. /**
  25849. * Returns the offset (integer).
  25850. */
  25851. VertexBuffer.prototype.getOffset = function () {
  25852. return this._offset;
  25853. };
  25854. /**
  25855. * Returns the VertexBuffer total size (integer).
  25856. */
  25857. VertexBuffer.prototype.getSize = function () {
  25858. return this._size;
  25859. };
  25860. /**
  25861. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  25862. */
  25863. VertexBuffer.prototype.getIsInstanced = function () {
  25864. return this._instanced;
  25865. };
  25866. /**
  25867. * Returns the instancing divisor, zero for non-instanced (integer).
  25868. */
  25869. VertexBuffer.prototype.getInstanceDivisor = function () {
  25870. return this._instanceDivisor;
  25871. };
  25872. // Methods
  25873. /**
  25874. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  25875. * Returns the created WebGLBuffer.
  25876. */
  25877. VertexBuffer.prototype.create = function (data) {
  25878. return this._buffer.create(data);
  25879. };
  25880. /**
  25881. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25882. * This function will create a new buffer if the current one is not updatable
  25883. * Returns the updated WebGLBuffer.
  25884. */
  25885. VertexBuffer.prototype.update = function (data) {
  25886. return this._buffer.update(data);
  25887. };
  25888. /**
  25889. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25890. * Returns the directly updated WebGLBuffer.
  25891. */
  25892. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  25893. return this._buffer.updateDirectly(data, offset);
  25894. };
  25895. /**
  25896. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  25897. */
  25898. VertexBuffer.prototype.dispose = function () {
  25899. if (this._ownsBuffer) {
  25900. this._buffer.dispose();
  25901. }
  25902. };
  25903. Object.defineProperty(VertexBuffer, "PositionKind", {
  25904. get: function () {
  25905. return VertexBuffer._PositionKind;
  25906. },
  25907. enumerable: true,
  25908. configurable: true
  25909. });
  25910. Object.defineProperty(VertexBuffer, "NormalKind", {
  25911. get: function () {
  25912. return VertexBuffer._NormalKind;
  25913. },
  25914. enumerable: true,
  25915. configurable: true
  25916. });
  25917. Object.defineProperty(VertexBuffer, "TangentKind", {
  25918. get: function () {
  25919. return VertexBuffer._TangentKind;
  25920. },
  25921. enumerable: true,
  25922. configurable: true
  25923. });
  25924. Object.defineProperty(VertexBuffer, "UVKind", {
  25925. get: function () {
  25926. return VertexBuffer._UVKind;
  25927. },
  25928. enumerable: true,
  25929. configurable: true
  25930. });
  25931. Object.defineProperty(VertexBuffer, "UV2Kind", {
  25932. get: function () {
  25933. return VertexBuffer._UV2Kind;
  25934. },
  25935. enumerable: true,
  25936. configurable: true
  25937. });
  25938. Object.defineProperty(VertexBuffer, "UV3Kind", {
  25939. get: function () {
  25940. return VertexBuffer._UV3Kind;
  25941. },
  25942. enumerable: true,
  25943. configurable: true
  25944. });
  25945. Object.defineProperty(VertexBuffer, "UV4Kind", {
  25946. get: function () {
  25947. return VertexBuffer._UV4Kind;
  25948. },
  25949. enumerable: true,
  25950. configurable: true
  25951. });
  25952. Object.defineProperty(VertexBuffer, "UV5Kind", {
  25953. get: function () {
  25954. return VertexBuffer._UV5Kind;
  25955. },
  25956. enumerable: true,
  25957. configurable: true
  25958. });
  25959. Object.defineProperty(VertexBuffer, "UV6Kind", {
  25960. get: function () {
  25961. return VertexBuffer._UV6Kind;
  25962. },
  25963. enumerable: true,
  25964. configurable: true
  25965. });
  25966. Object.defineProperty(VertexBuffer, "ColorKind", {
  25967. get: function () {
  25968. return VertexBuffer._ColorKind;
  25969. },
  25970. enumerable: true,
  25971. configurable: true
  25972. });
  25973. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  25974. get: function () {
  25975. return VertexBuffer._MatricesIndicesKind;
  25976. },
  25977. enumerable: true,
  25978. configurable: true
  25979. });
  25980. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  25981. get: function () {
  25982. return VertexBuffer._MatricesWeightsKind;
  25983. },
  25984. enumerable: true,
  25985. configurable: true
  25986. });
  25987. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  25988. get: function () {
  25989. return VertexBuffer._MatricesIndicesExtraKind;
  25990. },
  25991. enumerable: true,
  25992. configurable: true
  25993. });
  25994. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  25995. get: function () {
  25996. return VertexBuffer._MatricesWeightsExtraKind;
  25997. },
  25998. enumerable: true,
  25999. configurable: true
  26000. });
  26001. /**
  26002. * Deduces the stride given a kind.
  26003. * @param kind The kind string to deduce
  26004. * @returns The deduced stride
  26005. */
  26006. VertexBuffer.DeduceStride = function (kind) {
  26007. switch (kind) {
  26008. case VertexBuffer.UVKind:
  26009. case VertexBuffer.UV2Kind:
  26010. case VertexBuffer.UV3Kind:
  26011. case VertexBuffer.UV4Kind:
  26012. case VertexBuffer.UV5Kind:
  26013. case VertexBuffer.UV6Kind:
  26014. return 2;
  26015. case VertexBuffer.NormalKind:
  26016. case VertexBuffer.PositionKind:
  26017. return 3;
  26018. case VertexBuffer.ColorKind:
  26019. case VertexBuffer.MatricesIndicesKind:
  26020. case VertexBuffer.MatricesIndicesExtraKind:
  26021. case VertexBuffer.MatricesWeightsKind:
  26022. case VertexBuffer.MatricesWeightsExtraKind:
  26023. case VertexBuffer.TangentKind:
  26024. return 4;
  26025. default:
  26026. throw new Error("Invalid kind '" + kind + "'");
  26027. }
  26028. };
  26029. // Enums
  26030. VertexBuffer._PositionKind = "position";
  26031. VertexBuffer._NormalKind = "normal";
  26032. VertexBuffer._TangentKind = "tangent";
  26033. VertexBuffer._UVKind = "uv";
  26034. VertexBuffer._UV2Kind = "uv2";
  26035. VertexBuffer._UV3Kind = "uv3";
  26036. VertexBuffer._UV4Kind = "uv4";
  26037. VertexBuffer._UV5Kind = "uv5";
  26038. VertexBuffer._UV6Kind = "uv6";
  26039. VertexBuffer._ColorKind = "color";
  26040. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  26041. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  26042. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  26043. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  26044. return VertexBuffer;
  26045. }());
  26046. BABYLON.VertexBuffer = VertexBuffer;
  26047. })(BABYLON || (BABYLON = {}));
  26048. //# sourceMappingURL=babylon.vertexBuffer.js.map
  26049. var BABYLON;
  26050. (function (BABYLON) {
  26051. /**
  26052. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  26053. */
  26054. var DummyInternalTextureTracker = /** @class */ (function () {
  26055. function DummyInternalTextureTracker() {
  26056. /**
  26057. * Gets or set the previous tracker in the list
  26058. */
  26059. this.previous = null;
  26060. /**
  26061. * Gets or set the next tracker in the list
  26062. */
  26063. this.next = null;
  26064. }
  26065. return DummyInternalTextureTracker;
  26066. }());
  26067. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  26068. })(BABYLON || (BABYLON = {}));
  26069. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26070. var BABYLON;
  26071. (function (BABYLON) {
  26072. /**
  26073. * Class used to store data associated with WebGL texture data for the engine
  26074. * This class should not be used directly
  26075. */
  26076. var InternalTexture = /** @class */ (function () {
  26077. /**
  26078. * Creates a new InternalTexture
  26079. * @param engine defines the engine to use
  26080. * @param dataSource defines the type of data that will be used
  26081. */
  26082. function InternalTexture(engine, dataSource) {
  26083. /**
  26084. * Observable called when the texture is loaded
  26085. */
  26086. this.onLoadedObservable = new BABYLON.Observable();
  26087. /**
  26088. * Gets or set the previous tracker in the list
  26089. */
  26090. this.previous = null;
  26091. /**
  26092. * Gets or set the next tracker in the list
  26093. */
  26094. this.next = null;
  26095. // Private
  26096. /** @ignore */
  26097. this._initialSlot = -1;
  26098. /** @ignore */
  26099. this._designatedSlot = -1;
  26100. /** @ignore */
  26101. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26102. /** @ignore */
  26103. this._comparisonFunction = 0;
  26104. /** @ignore */
  26105. this._references = 1;
  26106. this._engine = engine;
  26107. this._dataSource = dataSource;
  26108. this._webGLTexture = engine._createTexture();
  26109. }
  26110. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26111. /**
  26112. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26113. */
  26114. get: function () {
  26115. return this._dataSource;
  26116. },
  26117. enumerable: true,
  26118. configurable: true
  26119. });
  26120. /**
  26121. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26122. */
  26123. InternalTexture.prototype.incrementReferences = function () {
  26124. this._references++;
  26125. };
  26126. /**
  26127. * Change the size of the texture (not the size of the content)
  26128. * @param width defines the new width
  26129. * @param height defines the new height
  26130. * @param depth defines the new depth (1 by default)
  26131. */
  26132. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26133. if (depth === void 0) { depth = 1; }
  26134. this.width = width;
  26135. this.height = height;
  26136. this.depth = depth;
  26137. this.baseWidth = width;
  26138. this.baseHeight = height;
  26139. this.baseDepth = depth;
  26140. this._size = width * height * depth;
  26141. };
  26142. /** @ignore */
  26143. InternalTexture.prototype._rebuild = function () {
  26144. var _this = this;
  26145. var proxy;
  26146. this.isReady = false;
  26147. this._cachedCoordinatesMode = null;
  26148. this._cachedWrapU = null;
  26149. this._cachedWrapV = null;
  26150. this._cachedAnisotropicFilteringLevel = null;
  26151. switch (this._dataSource) {
  26152. case InternalTexture.DATASOURCE_TEMP:
  26153. return;
  26154. case InternalTexture.DATASOURCE_URL:
  26155. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26156. _this.isReady = true;
  26157. }, null, this._buffer, undefined, this.format);
  26158. proxy._swapAndDie(this);
  26159. return;
  26160. case InternalTexture.DATASOURCE_RAW:
  26161. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26162. proxy._swapAndDie(this);
  26163. this.isReady = true;
  26164. return;
  26165. case InternalTexture.DATASOURCE_RAW3D:
  26166. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26167. proxy._swapAndDie(this);
  26168. this.isReady = true;
  26169. return;
  26170. case InternalTexture.DATASOURCE_DYNAMIC:
  26171. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26172. proxy._swapAndDie(this);
  26173. // The engine will make sure to update content so no need to flag it as isReady = true
  26174. return;
  26175. case InternalTexture.DATASOURCE_RENDERTARGET:
  26176. var options = new BABYLON.RenderTargetCreationOptions();
  26177. options.generateDepthBuffer = this._generateDepthBuffer;
  26178. options.generateMipMaps = this.generateMipMaps;
  26179. options.generateStencilBuffer = this._generateStencilBuffer;
  26180. options.samplingMode = this.samplingMode;
  26181. options.type = this.type;
  26182. if (this.isCube) {
  26183. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26184. }
  26185. else {
  26186. var size = {
  26187. width: this.width,
  26188. height: this.height
  26189. };
  26190. proxy = this._engine.createRenderTargetTexture(size, options);
  26191. }
  26192. proxy._swapAndDie(this);
  26193. this.isReady = true;
  26194. return;
  26195. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26196. var depthTextureOptions = {
  26197. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26198. comparisonFunction: this._comparisonFunction,
  26199. generateStencil: this._generateStencilBuffer,
  26200. };
  26201. if (this.isCube) {
  26202. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26203. }
  26204. else {
  26205. proxy = this._engine.createDepthStencilCubeTexture(this.width, depthTextureOptions);
  26206. }
  26207. proxy._swapAndDie(this);
  26208. this.isReady = true;
  26209. return;
  26210. case InternalTexture.DATASOURCE_CUBE:
  26211. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26212. _this.isReady = true;
  26213. }, null, this.format, this._extension);
  26214. proxy._swapAndDie(this);
  26215. return;
  26216. case InternalTexture.DATASOURCE_CUBERAW:
  26217. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26218. proxy._swapAndDie(this);
  26219. this.isReady = true;
  26220. return;
  26221. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26222. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26223. if (proxy) {
  26224. proxy._swapAndDie(_this);
  26225. }
  26226. _this.isReady = true;
  26227. }, null, this.format, this._extension);
  26228. return;
  26229. }
  26230. };
  26231. InternalTexture.prototype._swapAndDie = function (target) {
  26232. target._webGLTexture = this._webGLTexture;
  26233. if (this._framebuffer) {
  26234. target._framebuffer = this._framebuffer;
  26235. }
  26236. if (this._depthStencilBuffer) {
  26237. target._depthStencilBuffer = this._depthStencilBuffer;
  26238. }
  26239. if (this._lodTextureHigh) {
  26240. if (target._lodTextureHigh) {
  26241. target._lodTextureHigh.dispose();
  26242. }
  26243. target._lodTextureHigh = this._lodTextureHigh;
  26244. }
  26245. if (this._lodTextureMid) {
  26246. if (target._lodTextureMid) {
  26247. target._lodTextureMid.dispose();
  26248. }
  26249. target._lodTextureMid = this._lodTextureMid;
  26250. }
  26251. if (this._lodTextureLow) {
  26252. if (target._lodTextureLow) {
  26253. target._lodTextureLow.dispose();
  26254. }
  26255. target._lodTextureLow = this._lodTextureLow;
  26256. }
  26257. var cache = this._engine.getLoadedTexturesCache();
  26258. var index = cache.indexOf(this);
  26259. if (index !== -1) {
  26260. cache.splice(index, 1);
  26261. }
  26262. };
  26263. /**
  26264. * Dispose the current allocated resources
  26265. */
  26266. InternalTexture.prototype.dispose = function () {
  26267. if (!this._webGLTexture) {
  26268. return;
  26269. }
  26270. this._references--;
  26271. if (this._references === 0) {
  26272. this._engine._releaseTexture(this);
  26273. this._webGLTexture = null;
  26274. this.previous = null;
  26275. this.next = null;
  26276. }
  26277. };
  26278. /**
  26279. * The source of the texture data is unknown
  26280. */
  26281. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26282. /**
  26283. * Texture data comes from an URL
  26284. */
  26285. InternalTexture.DATASOURCE_URL = 1;
  26286. /**
  26287. * Texture data is only used for temporary storage
  26288. */
  26289. InternalTexture.DATASOURCE_TEMP = 2;
  26290. /**
  26291. * Texture data comes from raw data (ArrayBuffer)
  26292. */
  26293. InternalTexture.DATASOURCE_RAW = 3;
  26294. /**
  26295. * Texture content is dynamic (video or dynamic texture)
  26296. */
  26297. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26298. /**
  26299. * Texture content is generated by rendering to it
  26300. */
  26301. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26302. /**
  26303. * Texture content is part of a multi render target process
  26304. */
  26305. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26306. /**
  26307. * Texture data comes from a cube data file
  26308. */
  26309. InternalTexture.DATASOURCE_CUBE = 7;
  26310. /**
  26311. * Texture data comes from a raw cube data
  26312. */
  26313. InternalTexture.DATASOURCE_CUBERAW = 8;
  26314. /**
  26315. * Texture data come from a prefiltered cube data file
  26316. */
  26317. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26318. /**
  26319. * Texture content is raw 3D data
  26320. */
  26321. InternalTexture.DATASOURCE_RAW3D = 10;
  26322. /**
  26323. * Texture content is a depth texture
  26324. */
  26325. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26326. return InternalTexture;
  26327. }());
  26328. BABYLON.InternalTexture = InternalTexture;
  26329. })(BABYLON || (BABYLON = {}));
  26330. //# sourceMappingURL=babylon.internalTexture.js.map
  26331. var BABYLON;
  26332. (function (BABYLON) {
  26333. var BaseTexture = /** @class */ (function () {
  26334. function BaseTexture(scene) {
  26335. this._hasAlpha = false;
  26336. this.getAlphaFromRGB = false;
  26337. this.level = 1;
  26338. this.coordinatesIndex = 0;
  26339. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26340. /**
  26341. * | Value | Type | Description |
  26342. * | ----- | ------------------ | ----------- |
  26343. * | 0 | CLAMP_ADDRESSMODE | |
  26344. * | 1 | WRAP_ADDRESSMODE | |
  26345. * | 2 | MIRROR_ADDRESSMODE | |
  26346. */
  26347. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26348. /**
  26349. * | Value | Type | Description |
  26350. * | ----- | ------------------ | ----------- |
  26351. * | 0 | CLAMP_ADDRESSMODE | |
  26352. * | 1 | WRAP_ADDRESSMODE | |
  26353. * | 2 | MIRROR_ADDRESSMODE | |
  26354. */
  26355. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26356. /**
  26357. * | Value | Type | Description |
  26358. * | ----- | ------------------ | ----------- |
  26359. * | 0 | CLAMP_ADDRESSMODE | |
  26360. * | 1 | WRAP_ADDRESSMODE | |
  26361. * | 2 | MIRROR_ADDRESSMODE | |
  26362. */
  26363. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26364. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26365. this.isCube = false;
  26366. this.is3D = false;
  26367. this.gammaSpace = true;
  26368. this.invertZ = false;
  26369. this.lodLevelInAlpha = false;
  26370. this.lodGenerationOffset = 0.0;
  26371. this.lodGenerationScale = 0.8;
  26372. this.isRenderTarget = false;
  26373. this.animations = new Array();
  26374. /**
  26375. * An event triggered when the texture is disposed.
  26376. * @type {BABYLON.Observable}
  26377. */
  26378. this.onDisposeObservable = new BABYLON.Observable();
  26379. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26380. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26381. if (this._scene) {
  26382. this._scene.textures.push(this);
  26383. }
  26384. this._uid = null;
  26385. }
  26386. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26387. get: function () {
  26388. return this._hasAlpha;
  26389. },
  26390. set: function (value) {
  26391. if (this._hasAlpha === value) {
  26392. return;
  26393. }
  26394. this._hasAlpha = value;
  26395. if (this._scene) {
  26396. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26397. }
  26398. },
  26399. enumerable: true,
  26400. configurable: true
  26401. });
  26402. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26403. get: function () {
  26404. return this._coordinatesMode;
  26405. },
  26406. /**
  26407. * How a texture is mapped.
  26408. *
  26409. * | Value | Type | Description |
  26410. * | ----- | ----------------------------------- | ----------- |
  26411. * | 0 | EXPLICIT_MODE | |
  26412. * | 1 | SPHERICAL_MODE | |
  26413. * | 2 | PLANAR_MODE | |
  26414. * | 3 | CUBIC_MODE | |
  26415. * | 4 | PROJECTION_MODE | |
  26416. * | 5 | SKYBOX_MODE | |
  26417. * | 6 | INVCUBIC_MODE | |
  26418. * | 7 | EQUIRECTANGULAR_MODE | |
  26419. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26420. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26421. */
  26422. set: function (value) {
  26423. if (this._coordinatesMode === value) {
  26424. return;
  26425. }
  26426. this._coordinatesMode = value;
  26427. if (this._scene) {
  26428. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26429. }
  26430. },
  26431. enumerable: true,
  26432. configurable: true
  26433. });
  26434. Object.defineProperty(BaseTexture.prototype, "uid", {
  26435. get: function () {
  26436. if (!this._uid) {
  26437. this._uid = BABYLON.Tools.RandomId();
  26438. }
  26439. return this._uid;
  26440. },
  26441. enumerable: true,
  26442. configurable: true
  26443. });
  26444. BaseTexture.prototype.toString = function () {
  26445. return this.name;
  26446. };
  26447. BaseTexture.prototype.getClassName = function () {
  26448. return "BaseTexture";
  26449. };
  26450. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26451. set: function (callback) {
  26452. if (this._onDisposeObserver) {
  26453. this.onDisposeObservable.remove(this._onDisposeObserver);
  26454. }
  26455. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26456. },
  26457. enumerable: true,
  26458. configurable: true
  26459. });
  26460. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26461. get: function () {
  26462. return true;
  26463. },
  26464. enumerable: true,
  26465. configurable: true
  26466. });
  26467. BaseTexture.prototype.getScene = function () {
  26468. return this._scene;
  26469. };
  26470. BaseTexture.prototype.getTextureMatrix = function () {
  26471. return BABYLON.Matrix.IdentityReadOnly;
  26472. };
  26473. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26474. return BABYLON.Matrix.IdentityReadOnly;
  26475. };
  26476. BaseTexture.prototype.getInternalTexture = function () {
  26477. return this._texture;
  26478. };
  26479. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  26480. return !this.isBlocking || this.isReady();
  26481. };
  26482. BaseTexture.prototype.isReady = function () {
  26483. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26484. this.delayLoad();
  26485. return false;
  26486. }
  26487. if (this._texture) {
  26488. return this._texture.isReady;
  26489. }
  26490. return false;
  26491. };
  26492. BaseTexture.prototype.getSize = function () {
  26493. if (this._texture && this._texture.width) {
  26494. return new BABYLON.Size(this._texture.width, this._texture.height);
  26495. }
  26496. if (this._texture && this._texture._size) {
  26497. return new BABYLON.Size(this._texture._size, this._texture._size);
  26498. }
  26499. return BABYLON.Size.Zero();
  26500. };
  26501. BaseTexture.prototype.getBaseSize = function () {
  26502. if (!this.isReady() || !this._texture)
  26503. return BABYLON.Size.Zero();
  26504. if (this._texture._size) {
  26505. return new BABYLON.Size(this._texture._size, this._texture._size);
  26506. }
  26507. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  26508. };
  26509. BaseTexture.prototype.scale = function (ratio) {
  26510. };
  26511. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26512. get: function () {
  26513. return false;
  26514. },
  26515. enumerable: true,
  26516. configurable: true
  26517. });
  26518. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  26519. if (!this._scene) {
  26520. return null;
  26521. }
  26522. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26523. for (var index = 0; index < texturesCache.length; index++) {
  26524. var texturesCacheEntry = texturesCache[index];
  26525. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  26526. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  26527. texturesCacheEntry.incrementReferences();
  26528. return texturesCacheEntry;
  26529. }
  26530. }
  26531. }
  26532. return null;
  26533. };
  26534. BaseTexture.prototype._rebuild = function () {
  26535. };
  26536. BaseTexture.prototype.delayLoad = function () {
  26537. };
  26538. BaseTexture.prototype.clone = function () {
  26539. return null;
  26540. };
  26541. Object.defineProperty(BaseTexture.prototype, "textureType", {
  26542. get: function () {
  26543. if (!this._texture) {
  26544. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26545. }
  26546. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26547. },
  26548. enumerable: true,
  26549. configurable: true
  26550. });
  26551. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  26552. get: function () {
  26553. if (!this._texture) {
  26554. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26555. }
  26556. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26557. },
  26558. enumerable: true,
  26559. configurable: true
  26560. });
  26561. BaseTexture.prototype.readPixels = function (faceIndex) {
  26562. if (faceIndex === void 0) { faceIndex = 0; }
  26563. if (!this._texture) {
  26564. return null;
  26565. }
  26566. var size = this.getSize();
  26567. var scene = this.getScene();
  26568. if (!scene) {
  26569. return null;
  26570. }
  26571. var engine = scene.getEngine();
  26572. if (this._texture.isCube) {
  26573. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  26574. }
  26575. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  26576. };
  26577. BaseTexture.prototype.releaseInternalTexture = function () {
  26578. if (this._texture) {
  26579. this._texture.dispose();
  26580. this._texture = null;
  26581. }
  26582. };
  26583. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  26584. get: function () {
  26585. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  26586. return null;
  26587. }
  26588. if (!this._texture._sphericalPolynomial) {
  26589. this._texture._sphericalPolynomial =
  26590. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  26591. }
  26592. return this._texture._sphericalPolynomial;
  26593. },
  26594. set: function (value) {
  26595. if (this._texture) {
  26596. this._texture._sphericalPolynomial = value;
  26597. }
  26598. },
  26599. enumerable: true,
  26600. configurable: true
  26601. });
  26602. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  26603. get: function () {
  26604. if (this._texture) {
  26605. return this._texture._lodTextureHigh;
  26606. }
  26607. return null;
  26608. },
  26609. enumerable: true,
  26610. configurable: true
  26611. });
  26612. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  26613. get: function () {
  26614. if (this._texture) {
  26615. return this._texture._lodTextureMid;
  26616. }
  26617. return null;
  26618. },
  26619. enumerable: true,
  26620. configurable: true
  26621. });
  26622. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  26623. get: function () {
  26624. if (this._texture) {
  26625. return this._texture._lodTextureLow;
  26626. }
  26627. return null;
  26628. },
  26629. enumerable: true,
  26630. configurable: true
  26631. });
  26632. BaseTexture.prototype.dispose = function () {
  26633. if (!this._scene) {
  26634. return;
  26635. }
  26636. // Animations
  26637. this._scene.stopAnimation(this);
  26638. // Remove from scene
  26639. this._scene._removePendingData(this);
  26640. var index = this._scene.textures.indexOf(this);
  26641. if (index >= 0) {
  26642. this._scene.textures.splice(index, 1);
  26643. }
  26644. if (this._texture === undefined) {
  26645. return;
  26646. }
  26647. // Release
  26648. this.releaseInternalTexture();
  26649. // Callback
  26650. this.onDisposeObservable.notifyObservers(this);
  26651. this.onDisposeObservable.clear();
  26652. };
  26653. BaseTexture.prototype.serialize = function () {
  26654. if (!this.name) {
  26655. return null;
  26656. }
  26657. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26658. // Animations
  26659. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26660. return serializationObject;
  26661. };
  26662. BaseTexture.WhenAllReady = function (textures, callback) {
  26663. var numRemaining = textures.length;
  26664. if (numRemaining === 0) {
  26665. callback();
  26666. return;
  26667. }
  26668. var _loop_1 = function () {
  26669. texture = textures[i];
  26670. if (texture.isReady()) {
  26671. if (--numRemaining === 0) {
  26672. callback();
  26673. }
  26674. }
  26675. else {
  26676. onLoadObservable = texture.onLoadObservable;
  26677. var onLoadCallback_1 = function () {
  26678. onLoadObservable.removeCallback(onLoadCallback_1);
  26679. if (--numRemaining === 0) {
  26680. callback();
  26681. }
  26682. };
  26683. onLoadObservable.add(onLoadCallback_1);
  26684. }
  26685. };
  26686. var texture, onLoadObservable;
  26687. for (var i = 0; i < textures.length; i++) {
  26688. _loop_1();
  26689. }
  26690. };
  26691. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  26692. __decorate([
  26693. BABYLON.serialize()
  26694. ], BaseTexture.prototype, "name", void 0);
  26695. __decorate([
  26696. BABYLON.serialize("hasAlpha")
  26697. ], BaseTexture.prototype, "_hasAlpha", void 0);
  26698. __decorate([
  26699. BABYLON.serialize()
  26700. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26701. __decorate([
  26702. BABYLON.serialize()
  26703. ], BaseTexture.prototype, "level", void 0);
  26704. __decorate([
  26705. BABYLON.serialize()
  26706. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26707. __decorate([
  26708. BABYLON.serialize("coordinatesMode")
  26709. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  26710. __decorate([
  26711. BABYLON.serialize()
  26712. ], BaseTexture.prototype, "wrapU", void 0);
  26713. __decorate([
  26714. BABYLON.serialize()
  26715. ], BaseTexture.prototype, "wrapV", void 0);
  26716. __decorate([
  26717. BABYLON.serialize()
  26718. ], BaseTexture.prototype, "wrapR", void 0);
  26719. __decorate([
  26720. BABYLON.serialize()
  26721. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26722. __decorate([
  26723. BABYLON.serialize()
  26724. ], BaseTexture.prototype, "isCube", void 0);
  26725. __decorate([
  26726. BABYLON.serialize()
  26727. ], BaseTexture.prototype, "is3D", void 0);
  26728. __decorate([
  26729. BABYLON.serialize()
  26730. ], BaseTexture.prototype, "gammaSpace", void 0);
  26731. __decorate([
  26732. BABYLON.serialize()
  26733. ], BaseTexture.prototype, "invertZ", void 0);
  26734. __decorate([
  26735. BABYLON.serialize()
  26736. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  26737. __decorate([
  26738. BABYLON.serialize()
  26739. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  26740. __decorate([
  26741. BABYLON.serialize()
  26742. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  26743. __decorate([
  26744. BABYLON.serialize()
  26745. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26746. return BaseTexture;
  26747. }());
  26748. BABYLON.BaseTexture = BaseTexture;
  26749. })(BABYLON || (BABYLON = {}));
  26750. //# sourceMappingURL=babylon.baseTexture.js.map
  26751. var BABYLON;
  26752. (function (BABYLON) {
  26753. var Texture = /** @class */ (function (_super) {
  26754. __extends(Texture, _super);
  26755. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26756. if (noMipmap === void 0) { noMipmap = false; }
  26757. if (invertY === void 0) { invertY = true; }
  26758. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26759. if (onLoad === void 0) { onLoad = null; }
  26760. if (onError === void 0) { onError = null; }
  26761. if (buffer === void 0) { buffer = null; }
  26762. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26763. var _this = _super.call(this, scene) || this;
  26764. _this.uOffset = 0;
  26765. _this.vOffset = 0;
  26766. _this.uScale = 1.0;
  26767. _this.vScale = 1.0;
  26768. _this.uAng = 0;
  26769. _this.vAng = 0;
  26770. _this.wAng = 0;
  26771. _this._isBlocking = true;
  26772. _this.name = url || "";
  26773. _this.url = url;
  26774. _this._noMipmap = noMipmap;
  26775. _this._invertY = invertY;
  26776. _this._samplingMode = samplingMode;
  26777. _this._buffer = buffer;
  26778. _this._deleteBuffer = deleteBuffer;
  26779. if (format) {
  26780. _this._format = format;
  26781. }
  26782. scene = _this.getScene();
  26783. if (!scene) {
  26784. return _this;
  26785. }
  26786. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  26787. var load = function () {
  26788. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  26789. _this.onLoadObservable.notifyObservers(_this);
  26790. }
  26791. if (onLoad) {
  26792. onLoad();
  26793. }
  26794. if (!_this.isBlocking && scene) {
  26795. scene.resetCachedMaterial();
  26796. }
  26797. };
  26798. if (!_this.url) {
  26799. _this._delayedOnLoad = load;
  26800. _this._delayedOnError = onError;
  26801. return _this;
  26802. }
  26803. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  26804. if (!_this._texture) {
  26805. if (!scene.useDelayedTextureLoading) {
  26806. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  26807. if (deleteBuffer) {
  26808. delete _this._buffer;
  26809. }
  26810. }
  26811. else {
  26812. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26813. _this._delayedOnLoad = load;
  26814. _this._delayedOnError = onError;
  26815. }
  26816. }
  26817. else {
  26818. if (_this._texture.isReady) {
  26819. BABYLON.Tools.SetImmediate(function () { return load(); });
  26820. }
  26821. else {
  26822. _this._texture.onLoadedObservable.add(load);
  26823. }
  26824. }
  26825. return _this;
  26826. }
  26827. Object.defineProperty(Texture.prototype, "noMipmap", {
  26828. get: function () {
  26829. return this._noMipmap;
  26830. },
  26831. enumerable: true,
  26832. configurable: true
  26833. });
  26834. Object.defineProperty(Texture.prototype, "isBlocking", {
  26835. get: function () {
  26836. return this._isBlocking;
  26837. },
  26838. set: function (value) {
  26839. this._isBlocking = value;
  26840. },
  26841. enumerable: true,
  26842. configurable: true
  26843. });
  26844. Object.defineProperty(Texture.prototype, "samplingMode", {
  26845. get: function () {
  26846. return this._samplingMode;
  26847. },
  26848. enumerable: true,
  26849. configurable: true
  26850. });
  26851. Texture.prototype.updateURL = function (url) {
  26852. this.url = url;
  26853. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26854. this.delayLoad();
  26855. };
  26856. Texture.prototype.delayLoad = function () {
  26857. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26858. return;
  26859. }
  26860. var scene = this.getScene();
  26861. if (!scene) {
  26862. return;
  26863. }
  26864. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26865. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  26866. if (!this._texture) {
  26867. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  26868. if (this._deleteBuffer) {
  26869. delete this._buffer;
  26870. }
  26871. }
  26872. else {
  26873. if (this._delayedOnLoad) {
  26874. if (this._texture.isReady) {
  26875. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  26876. }
  26877. else {
  26878. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  26879. }
  26880. }
  26881. }
  26882. this._delayedOnLoad = null;
  26883. this._delayedOnError = null;
  26884. };
  26885. Texture.prototype.updateSamplingMode = function (samplingMode) {
  26886. if (!this._texture) {
  26887. return;
  26888. }
  26889. var scene = this.getScene();
  26890. if (!scene) {
  26891. return;
  26892. }
  26893. this._samplingMode = samplingMode;
  26894. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  26895. };
  26896. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  26897. x *= this.uScale;
  26898. y *= this.vScale;
  26899. x -= 0.5 * this.uScale;
  26900. y -= 0.5 * this.vScale;
  26901. z -= 0.5;
  26902. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  26903. t.x += 0.5 * this.uScale + this.uOffset;
  26904. t.y += 0.5 * this.vScale + this.vOffset;
  26905. t.z += 0.5;
  26906. };
  26907. Texture.prototype.getTextureMatrix = function () {
  26908. var _this = this;
  26909. if (this.uOffset === this._cachedUOffset &&
  26910. this.vOffset === this._cachedVOffset &&
  26911. this.uScale === this._cachedUScale &&
  26912. this.vScale === this._cachedVScale &&
  26913. this.uAng === this._cachedUAng &&
  26914. this.vAng === this._cachedVAng &&
  26915. this.wAng === this._cachedWAng) {
  26916. return this._cachedTextureMatrix;
  26917. }
  26918. this._cachedUOffset = this.uOffset;
  26919. this._cachedVOffset = this.vOffset;
  26920. this._cachedUScale = this.uScale;
  26921. this._cachedVScale = this.vScale;
  26922. this._cachedUAng = this.uAng;
  26923. this._cachedVAng = this.vAng;
  26924. this._cachedWAng = this.wAng;
  26925. if (!this._cachedTextureMatrix) {
  26926. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26927. this._rowGenerationMatrix = new BABYLON.Matrix();
  26928. this._t0 = BABYLON.Vector3.Zero();
  26929. this._t1 = BABYLON.Vector3.Zero();
  26930. this._t2 = BABYLON.Vector3.Zero();
  26931. }
  26932. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  26933. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  26934. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  26935. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  26936. this._t1.subtractInPlace(this._t0);
  26937. this._t2.subtractInPlace(this._t0);
  26938. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26939. this._cachedTextureMatrix.m[0] = this._t1.x;
  26940. this._cachedTextureMatrix.m[1] = this._t1.y;
  26941. this._cachedTextureMatrix.m[2] = this._t1.z;
  26942. this._cachedTextureMatrix.m[4] = this._t2.x;
  26943. this._cachedTextureMatrix.m[5] = this._t2.y;
  26944. this._cachedTextureMatrix.m[6] = this._t2.z;
  26945. this._cachedTextureMatrix.m[8] = this._t0.x;
  26946. this._cachedTextureMatrix.m[9] = this._t0.y;
  26947. this._cachedTextureMatrix.m[10] = this._t0.z;
  26948. var scene = this.getScene();
  26949. if (!scene) {
  26950. return this._cachedTextureMatrix;
  26951. }
  26952. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26953. return mat.hasTexture(_this);
  26954. });
  26955. return this._cachedTextureMatrix;
  26956. };
  26957. Texture.prototype.getReflectionTextureMatrix = function () {
  26958. var _this = this;
  26959. var scene = this.getScene();
  26960. if (!scene) {
  26961. return this._cachedTextureMatrix;
  26962. }
  26963. if (this.uOffset === this._cachedUOffset &&
  26964. this.vOffset === this._cachedVOffset &&
  26965. this.uScale === this._cachedUScale &&
  26966. this.vScale === this._cachedVScale &&
  26967. this.coordinatesMode === this._cachedCoordinatesMode) {
  26968. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  26969. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  26970. return this._cachedTextureMatrix;
  26971. }
  26972. }
  26973. else {
  26974. return this._cachedTextureMatrix;
  26975. }
  26976. }
  26977. if (!this._cachedTextureMatrix) {
  26978. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26979. }
  26980. if (!this._projectionModeMatrix) {
  26981. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  26982. }
  26983. this._cachedUOffset = this.uOffset;
  26984. this._cachedVOffset = this.vOffset;
  26985. this._cachedUScale = this.uScale;
  26986. this._cachedVScale = this.vScale;
  26987. this._cachedCoordinatesMode = this.coordinatesMode;
  26988. switch (this.coordinatesMode) {
  26989. case Texture.PLANAR_MODE:
  26990. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26991. this._cachedTextureMatrix[0] = this.uScale;
  26992. this._cachedTextureMatrix[5] = this.vScale;
  26993. this._cachedTextureMatrix[12] = this.uOffset;
  26994. this._cachedTextureMatrix[13] = this.vOffset;
  26995. break;
  26996. case Texture.PROJECTION_MODE:
  26997. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  26998. this._projectionModeMatrix.m[0] = 0.5;
  26999. this._projectionModeMatrix.m[5] = -0.5;
  27000. this._projectionModeMatrix.m[10] = 0.0;
  27001. this._projectionModeMatrix.m[12] = 0.5;
  27002. this._projectionModeMatrix.m[13] = 0.5;
  27003. this._projectionModeMatrix.m[14] = 1.0;
  27004. this._projectionModeMatrix.m[15] = 1.0;
  27005. var projectionMatrix = scene.getProjectionMatrix();
  27006. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  27007. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27008. break;
  27009. default:
  27010. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27011. break;
  27012. }
  27013. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27014. return (mat.getActiveTextures().indexOf(_this) !== -1);
  27015. });
  27016. return this._cachedTextureMatrix;
  27017. };
  27018. Texture.prototype.clone = function () {
  27019. var _this = this;
  27020. return BABYLON.SerializationHelper.Clone(function () {
  27021. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27022. }, this);
  27023. };
  27024. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27025. get: function () {
  27026. if (!this._onLoadObservable) {
  27027. this._onLoadObservable = new BABYLON.Observable();
  27028. }
  27029. return this._onLoadObservable;
  27030. },
  27031. enumerable: true,
  27032. configurable: true
  27033. });
  27034. Texture.prototype.serialize = function () {
  27035. var serializationObject = _super.prototype.serialize.call(this);
  27036. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  27037. serializationObject.base64String = this._buffer;
  27038. serializationObject.name = serializationObject.name.replace("data:", "");
  27039. }
  27040. return serializationObject;
  27041. };
  27042. Texture.prototype.getClassName = function () {
  27043. return "Texture";
  27044. };
  27045. Texture.prototype.dispose = function () {
  27046. _super.prototype.dispose.call(this);
  27047. if (this.onLoadObservable) {
  27048. this.onLoadObservable.clear();
  27049. this._onLoadObservable = null;
  27050. }
  27051. this._delayedOnLoad = null;
  27052. this._delayedOnError = null;
  27053. };
  27054. // Statics
  27055. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27056. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27057. if (onLoad === void 0) { onLoad = null; }
  27058. if (onError === void 0) { onError = null; }
  27059. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27060. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27061. };
  27062. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27063. if (parsedTexture.customType) {
  27064. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27065. // Update Sampling Mode
  27066. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  27067. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  27068. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27069. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27070. }
  27071. }
  27072. return parsedCustomTexture;
  27073. }
  27074. if (parsedTexture.isCube) {
  27075. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27076. }
  27077. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27078. return null;
  27079. }
  27080. var texture = BABYLON.SerializationHelper.Parse(function () {
  27081. var generateMipMaps = true;
  27082. if (parsedTexture.noMipmap) {
  27083. generateMipMaps = false;
  27084. }
  27085. if (parsedTexture.mirrorPlane) {
  27086. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27087. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27088. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27089. return mirrorTexture;
  27090. }
  27091. else if (parsedTexture.isRenderTarget) {
  27092. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27093. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27094. return renderTargetTexture;
  27095. }
  27096. else {
  27097. var texture;
  27098. if (parsedTexture.base64String) {
  27099. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27100. }
  27101. else {
  27102. var url = rootUrl + parsedTexture.name;
  27103. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27104. url = parsedTexture.url;
  27105. }
  27106. texture = new Texture(url, scene, !generateMipMaps);
  27107. }
  27108. return texture;
  27109. }
  27110. }, parsedTexture, scene);
  27111. // Update Sampling Mode
  27112. if (parsedTexture.samplingMode) {
  27113. var sampling = parsedTexture.samplingMode;
  27114. if (texture._samplingMode !== sampling) {
  27115. texture.updateSamplingMode(sampling);
  27116. }
  27117. }
  27118. // Animations
  27119. if (parsedTexture.animations) {
  27120. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27121. var parsedAnimation = parsedTexture.animations[animationIndex];
  27122. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27123. }
  27124. }
  27125. return texture;
  27126. };
  27127. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27128. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27129. if (noMipmap === void 0) { noMipmap = false; }
  27130. if (invertY === void 0) { invertY = true; }
  27131. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27132. if (onLoad === void 0) { onLoad = null; }
  27133. if (onError === void 0) { onError = null; }
  27134. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27135. if (name.substr(0, 5) !== "data:") {
  27136. name = "data:" + name;
  27137. }
  27138. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27139. };
  27140. // Constants
  27141. Texture.NEAREST_SAMPLINGMODE = 1;
  27142. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27143. Texture.BILINEAR_SAMPLINGMODE = 2;
  27144. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27145. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27146. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27147. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27148. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27149. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27150. Texture.NEAREST_LINEAR = 7;
  27151. Texture.NEAREST_NEAREST = 8;
  27152. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27153. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27154. Texture.LINEAR_LINEAR = 11;
  27155. Texture.LINEAR_NEAREST = 12;
  27156. Texture.EXPLICIT_MODE = 0;
  27157. Texture.SPHERICAL_MODE = 1;
  27158. Texture.PLANAR_MODE = 2;
  27159. Texture.CUBIC_MODE = 3;
  27160. Texture.PROJECTION_MODE = 4;
  27161. Texture.SKYBOX_MODE = 5;
  27162. Texture.INVCUBIC_MODE = 6;
  27163. Texture.EQUIRECTANGULAR_MODE = 7;
  27164. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27165. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27166. Texture.CLAMP_ADDRESSMODE = 0;
  27167. Texture.WRAP_ADDRESSMODE = 1;
  27168. Texture.MIRROR_ADDRESSMODE = 2;
  27169. /**
  27170. * 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
  27171. */
  27172. Texture.UseSerializedUrlIfAny = false;
  27173. __decorate([
  27174. BABYLON.serialize()
  27175. ], Texture.prototype, "url", void 0);
  27176. __decorate([
  27177. BABYLON.serialize()
  27178. ], Texture.prototype, "uOffset", void 0);
  27179. __decorate([
  27180. BABYLON.serialize()
  27181. ], Texture.prototype, "vOffset", void 0);
  27182. __decorate([
  27183. BABYLON.serialize()
  27184. ], Texture.prototype, "uScale", void 0);
  27185. __decorate([
  27186. BABYLON.serialize()
  27187. ], Texture.prototype, "vScale", void 0);
  27188. __decorate([
  27189. BABYLON.serialize()
  27190. ], Texture.prototype, "uAng", void 0);
  27191. __decorate([
  27192. BABYLON.serialize()
  27193. ], Texture.prototype, "vAng", void 0);
  27194. __decorate([
  27195. BABYLON.serialize()
  27196. ], Texture.prototype, "wAng", void 0);
  27197. __decorate([
  27198. BABYLON.serialize()
  27199. ], Texture.prototype, "isBlocking", null);
  27200. return Texture;
  27201. }(BABYLON.BaseTexture));
  27202. BABYLON.Texture = Texture;
  27203. })(BABYLON || (BABYLON = {}));
  27204. //# sourceMappingURL=babylon.texture.js.map
  27205. var BABYLON;
  27206. (function (BABYLON) {
  27207. var _InstancesBatch = /** @class */ (function () {
  27208. function _InstancesBatch() {
  27209. this.mustReturn = false;
  27210. this.visibleInstances = new Array();
  27211. this.renderSelf = new Array();
  27212. }
  27213. return _InstancesBatch;
  27214. }());
  27215. BABYLON._InstancesBatch = _InstancesBatch;
  27216. var Mesh = /** @class */ (function (_super) {
  27217. __extends(Mesh, _super);
  27218. /**
  27219. * @constructor
  27220. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27221. * @param {Scene} scene The scene to add this mesh to.
  27222. * @param {Node} parent The parent of this mesh, if it has one
  27223. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27224. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27225. * When false, achieved by calling a clone(), also passing False.
  27226. * This will make creation of children, recursive.
  27227. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27228. */
  27229. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27230. if (scene === void 0) { scene = null; }
  27231. if (parent === void 0) { parent = null; }
  27232. if (source === void 0) { source = null; }
  27233. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27234. var _this = _super.call(this, name, scene) || this;
  27235. // Events
  27236. /**
  27237. * An event triggered before rendering the mesh
  27238. * @type {BABYLON.Observable}
  27239. */
  27240. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27241. /**
  27242. * An event triggered after rendering the mesh
  27243. * @type {BABYLON.Observable}
  27244. */
  27245. _this.onAfterRenderObservable = new BABYLON.Observable();
  27246. /**
  27247. * An event triggered before drawing the mesh
  27248. * @type {BABYLON.Observable}
  27249. */
  27250. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27251. // Members
  27252. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27253. _this.instances = new Array();
  27254. _this._LODLevels = new Array();
  27255. _this._visibleInstances = {};
  27256. _this._renderIdForInstances = new Array();
  27257. _this._batchCache = new _InstancesBatch();
  27258. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27259. // Use by builder only to know what orientation were the mesh build in.
  27260. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27261. _this.overrideMaterialSideOrientation = null;
  27262. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27263. // Will be used to save a source mesh reference, If any
  27264. _this._source = null;
  27265. scene = _this.getScene();
  27266. if (source) {
  27267. // Source mesh
  27268. _this._source = source;
  27269. // Geometry
  27270. if (source._geometry) {
  27271. source._geometry.applyToMesh(_this);
  27272. }
  27273. // Deep copy
  27274. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  27275. // Metadata
  27276. if (source.metadata && source.metadata.clone) {
  27277. _this.metadata = source.metadata.clone();
  27278. }
  27279. else {
  27280. _this.metadata = source.metadata;
  27281. }
  27282. // Tags
  27283. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27284. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27285. }
  27286. // Parent
  27287. _this.parent = source.parent;
  27288. // Pivot
  27289. _this.setPivotMatrix(source.getPivotMatrix());
  27290. _this.id = name + "." + source.id;
  27291. // Material
  27292. _this.material = source.material;
  27293. var index;
  27294. if (!doNotCloneChildren) {
  27295. // Children
  27296. var directDescendants = source.getDescendants(true);
  27297. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27298. var child = directDescendants[index_1];
  27299. if (child.clone) {
  27300. child.clone(name + "." + child.name, _this);
  27301. }
  27302. }
  27303. }
  27304. // Physics clone
  27305. var physicsEngine = _this.getScene().getPhysicsEngine();
  27306. if (clonePhysicsImpostor && physicsEngine) {
  27307. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27308. if (impostor) {
  27309. _this.physicsImpostor = impostor.clone(_this);
  27310. }
  27311. }
  27312. // Particles
  27313. for (index = 0; index < scene.particleSystems.length; index++) {
  27314. var system = scene.particleSystems[index];
  27315. if (system.emitter === source) {
  27316. system.clone(system.name, _this);
  27317. }
  27318. }
  27319. _this.computeWorldMatrix(true);
  27320. }
  27321. // Parent
  27322. if (parent !== null) {
  27323. _this.parent = parent;
  27324. }
  27325. return _this;
  27326. }
  27327. Object.defineProperty(Mesh, "FRONTSIDE", {
  27328. /**
  27329. * Mesh side orientation : usually the external or front surface
  27330. */
  27331. get: function () {
  27332. return Mesh._FRONTSIDE;
  27333. },
  27334. enumerable: true,
  27335. configurable: true
  27336. });
  27337. Object.defineProperty(Mesh, "BACKSIDE", {
  27338. /**
  27339. * Mesh side orientation : usually the internal or back surface
  27340. */
  27341. get: function () {
  27342. return Mesh._BACKSIDE;
  27343. },
  27344. enumerable: true,
  27345. configurable: true
  27346. });
  27347. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27348. /**
  27349. * Mesh side orientation : both internal and external or front and back surfaces
  27350. */
  27351. get: function () {
  27352. return Mesh._DOUBLESIDE;
  27353. },
  27354. enumerable: true,
  27355. configurable: true
  27356. });
  27357. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27358. /**
  27359. * Mesh side orientation : by default, `FRONTSIDE`
  27360. */
  27361. get: function () {
  27362. return Mesh._DEFAULTSIDE;
  27363. },
  27364. enumerable: true,
  27365. configurable: true
  27366. });
  27367. Object.defineProperty(Mesh, "NO_CAP", {
  27368. /**
  27369. * Mesh cap setting : no cap
  27370. */
  27371. get: function () {
  27372. return Mesh._NO_CAP;
  27373. },
  27374. enumerable: true,
  27375. configurable: true
  27376. });
  27377. Object.defineProperty(Mesh, "CAP_START", {
  27378. /**
  27379. * Mesh cap setting : one cap at the beginning of the mesh
  27380. */
  27381. get: function () {
  27382. return Mesh._CAP_START;
  27383. },
  27384. enumerable: true,
  27385. configurable: true
  27386. });
  27387. Object.defineProperty(Mesh, "CAP_END", {
  27388. /**
  27389. * Mesh cap setting : one cap at the end of the mesh
  27390. */
  27391. get: function () {
  27392. return Mesh._CAP_END;
  27393. },
  27394. enumerable: true,
  27395. configurable: true
  27396. });
  27397. Object.defineProperty(Mesh, "CAP_ALL", {
  27398. /**
  27399. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27400. */
  27401. get: function () {
  27402. return Mesh._CAP_ALL;
  27403. },
  27404. enumerable: true,
  27405. configurable: true
  27406. });
  27407. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27408. set: function (callback) {
  27409. if (this._onBeforeDrawObserver) {
  27410. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27411. }
  27412. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27413. },
  27414. enumerable: true,
  27415. configurable: true
  27416. });
  27417. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27418. get: function () {
  27419. return this._morphTargetManager;
  27420. },
  27421. set: function (value) {
  27422. if (this._morphTargetManager === value) {
  27423. return;
  27424. }
  27425. this._morphTargetManager = value;
  27426. this._syncGeometryWithMorphTargetManager();
  27427. },
  27428. enumerable: true,
  27429. configurable: true
  27430. });
  27431. Object.defineProperty(Mesh.prototype, "source", {
  27432. get: function () {
  27433. return this._source;
  27434. },
  27435. enumerable: true,
  27436. configurable: true
  27437. });
  27438. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27439. get: function () {
  27440. return this._unIndexed;
  27441. },
  27442. set: function (value) {
  27443. if (this._unIndexed !== value) {
  27444. this._unIndexed = value;
  27445. this._markSubMeshesAsAttributesDirty();
  27446. }
  27447. },
  27448. enumerable: true,
  27449. configurable: true
  27450. });
  27451. // Methods
  27452. /**
  27453. * Returns the string "Mesh".
  27454. */
  27455. Mesh.prototype.getClassName = function () {
  27456. return "Mesh";
  27457. };
  27458. /**
  27459. * Returns a string.
  27460. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27461. */
  27462. Mesh.prototype.toString = function (fullDetails) {
  27463. var ret = _super.prototype.toString.call(this, fullDetails);
  27464. ret += ", n vertices: " + this.getTotalVertices();
  27465. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  27466. if (this.animations) {
  27467. for (var i = 0; i < this.animations.length; i++) {
  27468. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  27469. }
  27470. }
  27471. if (fullDetails) {
  27472. if (this._geometry) {
  27473. var ib = this.getIndices();
  27474. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27475. if (vb && ib) {
  27476. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  27477. }
  27478. }
  27479. else {
  27480. ret += ", flat shading: UNKNOWN";
  27481. }
  27482. }
  27483. return ret;
  27484. };
  27485. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  27486. /**
  27487. * True if the mesh has some Levels Of Details (LOD).
  27488. * Returns a boolean.
  27489. */
  27490. get: function () {
  27491. return this._LODLevels.length > 0;
  27492. },
  27493. enumerable: true,
  27494. configurable: true
  27495. });
  27496. /**
  27497. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  27498. * @returns an array of {BABYLON.MeshLODLevel}
  27499. */
  27500. Mesh.prototype.getLODLevels = function () {
  27501. return this._LODLevels;
  27502. };
  27503. Mesh.prototype._sortLODLevels = function () {
  27504. this._LODLevels.sort(function (a, b) {
  27505. if (a.distance < b.distance) {
  27506. return 1;
  27507. }
  27508. if (a.distance > b.distance) {
  27509. return -1;
  27510. }
  27511. return 0;
  27512. });
  27513. };
  27514. /**
  27515. * Add a mesh as LOD level triggered at the given distance.
  27516. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27517. * @param {number} distance The distance from the center of the object to show this level
  27518. * @param {Mesh} mesh The mesh to be added as LOD level
  27519. * @return {Mesh} This mesh (for chaining)
  27520. */
  27521. Mesh.prototype.addLODLevel = function (distance, mesh) {
  27522. if (mesh && mesh._masterMesh) {
  27523. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  27524. return this;
  27525. }
  27526. var level = new BABYLON.MeshLODLevel(distance, mesh);
  27527. this._LODLevels.push(level);
  27528. if (mesh) {
  27529. mesh._masterMesh = this;
  27530. }
  27531. this._sortLODLevels();
  27532. return this;
  27533. };
  27534. /**
  27535. * Returns the LOD level mesh at the passed distance or null if not found.
  27536. * It is related to the method `addLODLevel(distance, mesh)`.
  27537. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27538. * Returns an object Mesh or `null`.
  27539. */
  27540. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  27541. for (var index = 0; index < this._LODLevels.length; index++) {
  27542. var level = this._LODLevels[index];
  27543. if (level.distance === distance) {
  27544. return level.mesh;
  27545. }
  27546. }
  27547. return null;
  27548. };
  27549. /**
  27550. * Remove a mesh from the LOD array
  27551. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27552. * @param {Mesh} mesh The mesh to be removed.
  27553. * @return {Mesh} This mesh (for chaining)
  27554. */
  27555. Mesh.prototype.removeLODLevel = function (mesh) {
  27556. for (var index = 0; index < this._LODLevels.length; index++) {
  27557. if (this._LODLevels[index].mesh === mesh) {
  27558. this._LODLevels.splice(index, 1);
  27559. if (mesh) {
  27560. mesh._masterMesh = null;
  27561. }
  27562. }
  27563. }
  27564. this._sortLODLevels();
  27565. return this;
  27566. };
  27567. /**
  27568. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  27569. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27570. */
  27571. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  27572. if (!this._LODLevels || this._LODLevels.length === 0) {
  27573. return this;
  27574. }
  27575. var bSphere;
  27576. if (boundingSphere) {
  27577. bSphere = boundingSphere;
  27578. }
  27579. else {
  27580. var boundingInfo = this.getBoundingInfo();
  27581. bSphere = boundingInfo.boundingSphere;
  27582. }
  27583. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  27584. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  27585. if (this.onLODLevelSelection) {
  27586. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  27587. }
  27588. return this;
  27589. }
  27590. for (var index = 0; index < this._LODLevels.length; index++) {
  27591. var level = this._LODLevels[index];
  27592. if (level.distance < distanceToCamera) {
  27593. if (level.mesh) {
  27594. level.mesh._preActivate();
  27595. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  27596. }
  27597. if (this.onLODLevelSelection) {
  27598. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  27599. }
  27600. return level.mesh;
  27601. }
  27602. }
  27603. if (this.onLODLevelSelection) {
  27604. this.onLODLevelSelection(distanceToCamera, this, this);
  27605. }
  27606. return this;
  27607. };
  27608. Object.defineProperty(Mesh.prototype, "geometry", {
  27609. /**
  27610. * Returns the mesh internal Geometry object.
  27611. */
  27612. get: function () {
  27613. return this._geometry;
  27614. },
  27615. enumerable: true,
  27616. configurable: true
  27617. });
  27618. /**
  27619. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  27620. */
  27621. Mesh.prototype.getTotalVertices = function () {
  27622. if (this._geometry === null || this._geometry === undefined) {
  27623. return 0;
  27624. }
  27625. return this._geometry.getTotalVertices();
  27626. };
  27627. /**
  27628. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  27629. * 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.
  27630. * You can force the copy with forceCopy === true
  27631. * Returns null if the mesh has no geometry or no vertex buffer.
  27632. * Possible `kind` values :
  27633. * - BABYLON.VertexBuffer.PositionKind
  27634. * - BABYLON.VertexBuffer.UVKind
  27635. * - BABYLON.VertexBuffer.UV2Kind
  27636. * - BABYLON.VertexBuffer.UV3Kind
  27637. * - BABYLON.VertexBuffer.UV4Kind
  27638. * - BABYLON.VertexBuffer.UV5Kind
  27639. * - BABYLON.VertexBuffer.UV6Kind
  27640. * - BABYLON.VertexBuffer.ColorKind
  27641. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27642. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27643. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27644. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27645. */
  27646. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27647. if (!this._geometry) {
  27648. return null;
  27649. }
  27650. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  27651. };
  27652. /**
  27653. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  27654. * Returns `null` if the mesh has no geometry.
  27655. * Possible `kind` values :
  27656. * - BABYLON.VertexBuffer.PositionKind
  27657. * - BABYLON.VertexBuffer.UVKind
  27658. * - BABYLON.VertexBuffer.UV2Kind
  27659. * - BABYLON.VertexBuffer.UV3Kind
  27660. * - BABYLON.VertexBuffer.UV4Kind
  27661. * - BABYLON.VertexBuffer.UV5Kind
  27662. * - BABYLON.VertexBuffer.UV6Kind
  27663. * - BABYLON.VertexBuffer.ColorKind
  27664. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27665. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27666. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27667. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27668. */
  27669. Mesh.prototype.getVertexBuffer = function (kind) {
  27670. if (!this._geometry) {
  27671. return null;
  27672. }
  27673. return this._geometry.getVertexBuffer(kind);
  27674. };
  27675. /**
  27676. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  27677. * Possible `kind` values :
  27678. * - BABYLON.VertexBuffer.PositionKind
  27679. * - BABYLON.VertexBuffer.UVKind
  27680. * - BABYLON.VertexBuffer.UV2Kind
  27681. * - BABYLON.VertexBuffer.UV3Kind
  27682. * - BABYLON.VertexBuffer.UV4Kind
  27683. * - BABYLON.VertexBuffer.UV5Kind
  27684. * - BABYLON.VertexBuffer.UV6Kind
  27685. * - BABYLON.VertexBuffer.ColorKind
  27686. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27687. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27688. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27689. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27690. */
  27691. Mesh.prototype.isVerticesDataPresent = function (kind) {
  27692. if (!this._geometry) {
  27693. if (this._delayInfo) {
  27694. return this._delayInfo.indexOf(kind) !== -1;
  27695. }
  27696. return false;
  27697. }
  27698. return this._geometry.isVerticesDataPresent(kind);
  27699. };
  27700. /**
  27701. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  27702. * Possible `kind` values :
  27703. * - BABYLON.VertexBuffer.PositionKind
  27704. * - BABYLON.VertexBuffer.UVKind
  27705. * - BABYLON.VertexBuffer.UV2Kind
  27706. * - BABYLON.VertexBuffer.UV3Kind
  27707. * - BABYLON.VertexBuffer.UV4Kind
  27708. * - BABYLON.VertexBuffer.UV5Kind
  27709. * - BABYLON.VertexBuffer.UV6Kind
  27710. * - BABYLON.VertexBuffer.ColorKind
  27711. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27712. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27713. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27714. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27715. */
  27716. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  27717. if (!this._geometry) {
  27718. if (this._delayInfo) {
  27719. return this._delayInfo.indexOf(kind) !== -1;
  27720. }
  27721. return false;
  27722. }
  27723. return this._geometry.isVertexBufferUpdatable(kind);
  27724. };
  27725. /**
  27726. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  27727. * Possible `kind` values :
  27728. * - BABYLON.VertexBuffer.PositionKind
  27729. * - BABYLON.VertexBuffer.UVKind
  27730. * - BABYLON.VertexBuffer.UV2Kind
  27731. * - BABYLON.VertexBuffer.UV3Kind
  27732. * - BABYLON.VertexBuffer.UV4Kind
  27733. * - BABYLON.VertexBuffer.UV5Kind
  27734. * - BABYLON.VertexBuffer.UV6Kind
  27735. * - BABYLON.VertexBuffer.ColorKind
  27736. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27737. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27738. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27739. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27740. */
  27741. Mesh.prototype.getVerticesDataKinds = function () {
  27742. if (!this._geometry) {
  27743. var result = new Array();
  27744. if (this._delayInfo) {
  27745. this._delayInfo.forEach(function (kind, index, array) {
  27746. result.push(kind);
  27747. });
  27748. }
  27749. return result;
  27750. }
  27751. return this._geometry.getVerticesDataKinds();
  27752. };
  27753. /**
  27754. * Returns a positive integer : the total number of indices in this mesh geometry.
  27755. * Returns zero if the mesh has no geometry.
  27756. */
  27757. Mesh.prototype.getTotalIndices = function () {
  27758. if (!this._geometry) {
  27759. return 0;
  27760. }
  27761. return this._geometry.getTotalIndices();
  27762. };
  27763. /**
  27764. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  27765. * 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.
  27766. * Returns an empty array if the mesh has no geometry.
  27767. */
  27768. Mesh.prototype.getIndices = function (copyWhenShared) {
  27769. if (!this._geometry) {
  27770. return [];
  27771. }
  27772. return this._geometry.getIndices(copyWhenShared);
  27773. };
  27774. Object.defineProperty(Mesh.prototype, "isBlocked", {
  27775. get: function () {
  27776. return this._masterMesh !== null && this._masterMesh !== undefined;
  27777. },
  27778. enumerable: true,
  27779. configurable: true
  27780. });
  27781. /**
  27782. * Determine if the current mesh is ready to be rendered
  27783. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  27784. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  27785. * @returns true if all associated assets are ready (material, textures, shaders)
  27786. */
  27787. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  27788. if (completeCheck === void 0) { completeCheck = false; }
  27789. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  27790. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27791. return false;
  27792. }
  27793. if (!_super.prototype.isReady.call(this, completeCheck)) {
  27794. return false;
  27795. }
  27796. if (!this.subMeshes || this.subMeshes.length === 0) {
  27797. return true;
  27798. }
  27799. if (!completeCheck) {
  27800. return true;
  27801. }
  27802. var engine = this.getEngine();
  27803. var scene = this.getScene();
  27804. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  27805. this.computeWorldMatrix();
  27806. var mat = this.material || scene.defaultMaterial;
  27807. if (mat) {
  27808. if (mat.storeEffectOnSubMeshes) {
  27809. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27810. var subMesh = _a[_i];
  27811. var effectiveMaterial = subMesh.getMaterial();
  27812. if (effectiveMaterial) {
  27813. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27814. return false;
  27815. }
  27816. }
  27817. }
  27818. }
  27819. else {
  27820. if (!mat.isReady(this, hardwareInstancedRendering)) {
  27821. return false;
  27822. }
  27823. }
  27824. }
  27825. // Shadows
  27826. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  27827. var light = _c[_b];
  27828. var generator = light.getShadowGenerator();
  27829. if (generator) {
  27830. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  27831. var subMesh = _e[_d];
  27832. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  27833. return false;
  27834. }
  27835. }
  27836. }
  27837. }
  27838. // LOD
  27839. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  27840. var lod = _g[_f];
  27841. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  27842. return false;
  27843. }
  27844. }
  27845. return true;
  27846. };
  27847. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  27848. /**
  27849. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  27850. * This property is pertinent only for updatable parametric shapes.
  27851. */
  27852. get: function () {
  27853. return this._areNormalsFrozen;
  27854. },
  27855. enumerable: true,
  27856. configurable: true
  27857. });
  27858. /**
  27859. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27860. * It has no effect at all on other shapes.
  27861. * It prevents the mesh normals from being recomputed on next `positions` array update.
  27862. * Returns the Mesh.
  27863. */
  27864. Mesh.prototype.freezeNormals = function () {
  27865. this._areNormalsFrozen = true;
  27866. return this;
  27867. };
  27868. /**
  27869. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27870. * It has no effect at all on other shapes.
  27871. * It reactivates the mesh normals computation if it was previously frozen.
  27872. * Returns the Mesh.
  27873. */
  27874. Mesh.prototype.unfreezeNormals = function () {
  27875. this._areNormalsFrozen = false;
  27876. return this;
  27877. };
  27878. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  27879. /**
  27880. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  27881. */
  27882. set: function (count) {
  27883. this._overridenInstanceCount = count;
  27884. },
  27885. enumerable: true,
  27886. configurable: true
  27887. });
  27888. // Methods
  27889. Mesh.prototype._preActivate = function () {
  27890. var sceneRenderId = this.getScene().getRenderId();
  27891. if (this._preActivateId === sceneRenderId) {
  27892. return this;
  27893. }
  27894. this._preActivateId = sceneRenderId;
  27895. this._visibleInstances = null;
  27896. return this;
  27897. };
  27898. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  27899. if (this._visibleInstances) {
  27900. this._visibleInstances.intermediateDefaultRenderId = renderId;
  27901. }
  27902. return this;
  27903. };
  27904. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  27905. if (!this._visibleInstances) {
  27906. this._visibleInstances = {};
  27907. this._visibleInstances.defaultRenderId = renderId;
  27908. this._visibleInstances.selfDefaultRenderId = this._renderId;
  27909. }
  27910. if (!this._visibleInstances[renderId]) {
  27911. this._visibleInstances[renderId] = new Array();
  27912. }
  27913. this._visibleInstances[renderId].push(instance);
  27914. return this;
  27915. };
  27916. /**
  27917. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  27918. * This means the mesh underlying bounding box and sphere are recomputed.
  27919. * Returns the Mesh.
  27920. */
  27921. Mesh.prototype.refreshBoundingInfo = function () {
  27922. return this._refreshBoundingInfo(false);
  27923. };
  27924. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  27925. if (this._boundingInfo && this._boundingInfo.isLocked) {
  27926. return this;
  27927. }
  27928. var data = this._getPositionData(applySkeleton);
  27929. if (data) {
  27930. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  27931. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27932. }
  27933. if (this.subMeshes) {
  27934. for (var index = 0; index < this.subMeshes.length; index++) {
  27935. this.subMeshes[index].refreshBoundingInfo();
  27936. }
  27937. }
  27938. this._updateBoundingInfo();
  27939. return this;
  27940. };
  27941. Mesh.prototype._getPositionData = function (applySkeleton) {
  27942. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27943. if (data && applySkeleton && this.skeleton) {
  27944. data = BABYLON.Tools.Slice(data);
  27945. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27946. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27947. if (matricesWeightsData && matricesIndicesData) {
  27948. var needExtras = this.numBoneInfluencers > 4;
  27949. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  27950. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  27951. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  27952. var tempVector = BABYLON.Tmp.Vector3[0];
  27953. var finalMatrix = BABYLON.Tmp.Matrix[0];
  27954. var tempMatrix = BABYLON.Tmp.Matrix[1];
  27955. var matWeightIdx = 0;
  27956. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  27957. finalMatrix.reset();
  27958. var inf;
  27959. var weight;
  27960. for (inf = 0; inf < 4; inf++) {
  27961. weight = matricesWeightsData[matWeightIdx + inf];
  27962. if (weight <= 0)
  27963. break;
  27964. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  27965. finalMatrix.addToSelf(tempMatrix);
  27966. }
  27967. if (needExtras) {
  27968. for (inf = 0; inf < 4; inf++) {
  27969. weight = matricesWeightsExtraData[matWeightIdx + inf];
  27970. if (weight <= 0)
  27971. break;
  27972. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  27973. finalMatrix.addToSelf(tempMatrix);
  27974. }
  27975. }
  27976. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  27977. tempVector.toArray(data, index);
  27978. }
  27979. }
  27980. }
  27981. return data;
  27982. };
  27983. Mesh.prototype._createGlobalSubMesh = function (force) {
  27984. var totalVertices = this.getTotalVertices();
  27985. if (!totalVertices || !this.getIndices()) {
  27986. return null;
  27987. }
  27988. // Check if we need to recreate the submeshes
  27989. if (this.subMeshes && this.subMeshes.length > 0) {
  27990. var ib = this.getIndices();
  27991. if (!ib) {
  27992. return null;
  27993. }
  27994. var totalIndices = ib.length;
  27995. var needToRecreate = false;
  27996. if (force) {
  27997. needToRecreate = true;
  27998. }
  27999. else {
  28000. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28001. var submesh = _a[_i];
  28002. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  28003. needToRecreate = true;
  28004. break;
  28005. }
  28006. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  28007. needToRecreate = true;
  28008. break;
  28009. }
  28010. }
  28011. }
  28012. if (!needToRecreate) {
  28013. return this.subMeshes[0];
  28014. }
  28015. }
  28016. this.releaseSubMeshes();
  28017. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  28018. };
  28019. Mesh.prototype.subdivide = function (count) {
  28020. if (count < 1) {
  28021. return;
  28022. }
  28023. var totalIndices = this.getTotalIndices();
  28024. var subdivisionSize = (totalIndices / count) | 0;
  28025. var offset = 0;
  28026. // Ensure that subdivisionSize is a multiple of 3
  28027. while (subdivisionSize % 3 !== 0) {
  28028. subdivisionSize++;
  28029. }
  28030. this.releaseSubMeshes();
  28031. for (var index = 0; index < count; index++) {
  28032. if (offset >= totalIndices) {
  28033. break;
  28034. }
  28035. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  28036. offset += subdivisionSize;
  28037. }
  28038. this.synchronizeInstances();
  28039. };
  28040. /**
  28041. * Sets the vertex data of the mesh geometry for the requested `kind`.
  28042. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  28043. * The `data` are either a numeric array either a Float32Array.
  28044. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  28045. * 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).
  28046. * Note that a new underlying VertexBuffer object is created each call.
  28047. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  28048. *
  28049. * Possible `kind` values :
  28050. * - BABYLON.VertexBuffer.PositionKind
  28051. * - BABYLON.VertexBuffer.UVKind
  28052. * - BABYLON.VertexBuffer.UV2Kind
  28053. * - BABYLON.VertexBuffer.UV3Kind
  28054. * - BABYLON.VertexBuffer.UV4Kind
  28055. * - BABYLON.VertexBuffer.UV5Kind
  28056. * - BABYLON.VertexBuffer.UV6Kind
  28057. * - BABYLON.VertexBuffer.ColorKind
  28058. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28059. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28060. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28061. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28062. *
  28063. * Returns the Mesh.
  28064. */
  28065. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28066. if (updatable === void 0) { updatable = false; }
  28067. if (!this._geometry) {
  28068. var vertexData = new BABYLON.VertexData();
  28069. vertexData.set(data, kind);
  28070. var scene = this.getScene();
  28071. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28072. }
  28073. else {
  28074. this._geometry.setVerticesData(kind, data, updatable, stride);
  28075. }
  28076. return this;
  28077. };
  28078. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28079. if (updatable === void 0) { updatable = true; }
  28080. var vb = this.getVertexBuffer(kind);
  28081. if (!vb || vb.isUpdatable() === updatable) {
  28082. return;
  28083. }
  28084. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28085. };
  28086. /**
  28087. * Sets the mesh VertexBuffer.
  28088. * Returns the Mesh.
  28089. */
  28090. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28091. if (!this._geometry) {
  28092. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28093. }
  28094. this._geometry.setVerticesBuffer(buffer);
  28095. return this;
  28096. };
  28097. /**
  28098. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28099. * If the mesh has no geometry, it is simply returned as it is.
  28100. * The `data` are either a numeric array either a Float32Array.
  28101. * No new underlying VertexBuffer object is created.
  28102. * 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.
  28103. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28104. *
  28105. * Possible `kind` values :
  28106. * - BABYLON.VertexBuffer.PositionKind
  28107. * - BABYLON.VertexBuffer.UVKind
  28108. * - BABYLON.VertexBuffer.UV2Kind
  28109. * - BABYLON.VertexBuffer.UV3Kind
  28110. * - BABYLON.VertexBuffer.UV4Kind
  28111. * - BABYLON.VertexBuffer.UV5Kind
  28112. * - BABYLON.VertexBuffer.UV6Kind
  28113. * - BABYLON.VertexBuffer.ColorKind
  28114. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28115. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28116. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28117. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28118. *
  28119. * Returns the Mesh.
  28120. */
  28121. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28122. if (!this._geometry) {
  28123. return this;
  28124. }
  28125. if (!makeItUnique) {
  28126. this._geometry.updateVerticesData(kind, data, updateExtends);
  28127. }
  28128. else {
  28129. this.makeGeometryUnique();
  28130. this.updateVerticesData(kind, data, updateExtends, false);
  28131. }
  28132. return this;
  28133. };
  28134. /**
  28135. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28136. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28137. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28138. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28139. * Returns the Mesh.
  28140. */
  28141. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28142. if (computeNormals === void 0) { computeNormals = true; }
  28143. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28144. if (!positions) {
  28145. return this;
  28146. }
  28147. positionFunction(positions);
  28148. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28149. if (computeNormals) {
  28150. var indices = this.getIndices();
  28151. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28152. if (!normals) {
  28153. return this;
  28154. }
  28155. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28156. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28157. }
  28158. return this;
  28159. };
  28160. /**
  28161. * Creates a un-shared specific occurence of the geometry for the mesh.
  28162. * Returns the Mesh.
  28163. */
  28164. Mesh.prototype.makeGeometryUnique = function () {
  28165. if (!this._geometry) {
  28166. return this;
  28167. }
  28168. var oldGeometry = this._geometry;
  28169. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28170. oldGeometry.releaseForMesh(this, true);
  28171. geometry.applyToMesh(this);
  28172. return this;
  28173. };
  28174. /**
  28175. * Sets the mesh indices.
  28176. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28177. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28178. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28179. * This method creates a new index buffer each call.
  28180. * Returns the Mesh.
  28181. */
  28182. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28183. if (totalVertices === void 0) { totalVertices = null; }
  28184. if (updatable === void 0) { updatable = false; }
  28185. if (!this._geometry) {
  28186. var vertexData = new BABYLON.VertexData();
  28187. vertexData.indices = indices;
  28188. var scene = this.getScene();
  28189. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28190. }
  28191. else {
  28192. this._geometry.setIndices(indices, totalVertices, updatable);
  28193. }
  28194. return this;
  28195. };
  28196. /**
  28197. * Update the current index buffer
  28198. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28199. * Returns the Mesh.
  28200. */
  28201. Mesh.prototype.updateIndices = function (indices, offset) {
  28202. if (!this._geometry) {
  28203. return this;
  28204. }
  28205. this._geometry.updateIndices(indices, offset);
  28206. return this;
  28207. };
  28208. /**
  28209. * Invert the geometry to move from a right handed system to a left handed one.
  28210. * Returns the Mesh.
  28211. */
  28212. Mesh.prototype.toLeftHanded = function () {
  28213. if (!this._geometry) {
  28214. return this;
  28215. }
  28216. this._geometry.toLeftHanded();
  28217. return this;
  28218. };
  28219. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28220. if (!this._geometry) {
  28221. return this;
  28222. }
  28223. var engine = this.getScene().getEngine();
  28224. // Wireframe
  28225. var indexToBind;
  28226. if (this._unIndexed) {
  28227. indexToBind = null;
  28228. }
  28229. else {
  28230. switch (fillMode) {
  28231. case BABYLON.Material.PointFillMode:
  28232. indexToBind = null;
  28233. break;
  28234. case BABYLON.Material.WireFrameFillMode:
  28235. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28236. break;
  28237. default:
  28238. case BABYLON.Material.TriangleFillMode:
  28239. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28240. break;
  28241. }
  28242. }
  28243. // VBOs
  28244. this._geometry._bind(effect, indexToBind);
  28245. return this;
  28246. };
  28247. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28248. if (alternate === void 0) { alternate = false; }
  28249. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28250. return this;
  28251. }
  28252. this.onBeforeDrawObservable.notifyObservers(this);
  28253. var scene = this.getScene();
  28254. var engine = scene.getEngine();
  28255. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28256. // or triangles as points
  28257. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28258. }
  28259. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28260. // Triangles as wireframe
  28261. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28262. }
  28263. else {
  28264. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28265. }
  28266. if (scene._isAlternateRenderingEnabled && !alternate) {
  28267. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28268. if (!effect || !scene.activeCamera) {
  28269. return this;
  28270. }
  28271. scene._switchToAlternateCameraConfiguration(true);
  28272. this._effectiveMaterial.bindView(effect);
  28273. this._effectiveMaterial.bindViewProjection(effect);
  28274. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28275. this._draw(subMesh, fillMode, instancesCount, true);
  28276. engine.setViewport(scene.activeCamera.viewport);
  28277. scene._switchToAlternateCameraConfiguration(false);
  28278. this._effectiveMaterial.bindView(effect);
  28279. this._effectiveMaterial.bindViewProjection(effect);
  28280. }
  28281. return this;
  28282. };
  28283. /**
  28284. * Registers for this mesh a javascript function called just before the rendering process.
  28285. * This function is passed the current mesh.
  28286. * Return the Mesh.
  28287. */
  28288. Mesh.prototype.registerBeforeRender = function (func) {
  28289. this.onBeforeRenderObservable.add(func);
  28290. return this;
  28291. };
  28292. /**
  28293. * Disposes a previously registered javascript function called before the rendering.
  28294. * This function is passed the current mesh.
  28295. * Returns the Mesh.
  28296. */
  28297. Mesh.prototype.unregisterBeforeRender = function (func) {
  28298. this.onBeforeRenderObservable.removeCallback(func);
  28299. return this;
  28300. };
  28301. /**
  28302. * Registers for this mesh a javascript function called just after the rendering is complete.
  28303. * This function is passed the current mesh.
  28304. * Returns the Mesh.
  28305. */
  28306. Mesh.prototype.registerAfterRender = function (func) {
  28307. this.onAfterRenderObservable.add(func);
  28308. return this;
  28309. };
  28310. /**
  28311. * Disposes a previously registered javascript function called after the rendering.
  28312. * This function is passed the current mesh.
  28313. * Return the Mesh.
  28314. */
  28315. Mesh.prototype.unregisterAfterRender = function (func) {
  28316. this.onAfterRenderObservable.removeCallback(func);
  28317. return this;
  28318. };
  28319. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28320. var scene = this.getScene();
  28321. this._batchCache.mustReturn = false;
  28322. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28323. this._batchCache.visibleInstances[subMeshId] = null;
  28324. if (this._visibleInstances) {
  28325. var currentRenderId = scene.getRenderId();
  28326. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28327. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28328. var selfRenderId = this._renderId;
  28329. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28330. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28331. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28332. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28333. }
  28334. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28335. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28336. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28337. this._batchCache.mustReturn = true;
  28338. return this._batchCache;
  28339. }
  28340. if (currentRenderId !== selfRenderId) {
  28341. this._batchCache.renderSelf[subMeshId] = false;
  28342. }
  28343. }
  28344. this._renderIdForInstances[subMeshId] = currentRenderId;
  28345. }
  28346. return this._batchCache;
  28347. };
  28348. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28349. var visibleInstances = batch.visibleInstances[subMesh._id];
  28350. if (!visibleInstances) {
  28351. return this;
  28352. }
  28353. var matricesCount = visibleInstances.length + 1;
  28354. var bufferSize = matricesCount * 16 * 4;
  28355. var currentInstancesBufferSize = this._instancesBufferSize;
  28356. var instancesBuffer = this._instancesBuffer;
  28357. while (this._instancesBufferSize < bufferSize) {
  28358. this._instancesBufferSize *= 2;
  28359. }
  28360. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28361. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28362. }
  28363. var offset = 0;
  28364. var instancesCount = 0;
  28365. var world = this.getWorldMatrix();
  28366. if (batch.renderSelf[subMesh._id]) {
  28367. world.copyToArray(this._instancesData, offset);
  28368. offset += 16;
  28369. instancesCount++;
  28370. }
  28371. if (visibleInstances) {
  28372. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28373. var instance = visibleInstances[instanceIndex];
  28374. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28375. offset += 16;
  28376. instancesCount++;
  28377. }
  28378. }
  28379. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28380. if (instancesBuffer) {
  28381. instancesBuffer.dispose();
  28382. }
  28383. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28384. this._instancesBuffer = instancesBuffer;
  28385. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28386. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28387. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28388. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28389. }
  28390. else {
  28391. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28392. }
  28393. this._bind(subMesh, effect, fillMode);
  28394. this._draw(subMesh, fillMode, instancesCount);
  28395. engine.unbindInstanceAttributes();
  28396. return this;
  28397. };
  28398. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28399. var scene = this.getScene();
  28400. var engine = scene.getEngine();
  28401. if (hardwareInstancedRendering) {
  28402. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28403. }
  28404. else {
  28405. if (batch.renderSelf[subMesh._id]) {
  28406. // Draw
  28407. if (onBeforeDraw) {
  28408. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28409. }
  28410. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28411. }
  28412. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28413. if (visibleInstancesForSubMesh) {
  28414. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28415. var instance = visibleInstancesForSubMesh[instanceIndex];
  28416. // World
  28417. var world = instance.getWorldMatrix();
  28418. if (onBeforeDraw) {
  28419. onBeforeDraw(true, world, effectiveMaterial);
  28420. }
  28421. // Draw
  28422. this._draw(subMesh, fillMode);
  28423. }
  28424. }
  28425. }
  28426. return this;
  28427. };
  28428. /**
  28429. * Triggers the draw call for the mesh.
  28430. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28431. * Returns the Mesh.
  28432. */
  28433. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28434. this.checkOcclusionQuery();
  28435. if (this._isOccluded) {
  28436. return this;
  28437. }
  28438. var scene = this.getScene();
  28439. // Managing instances
  28440. var batch = this._getInstancesRenderList(subMesh._id);
  28441. if (batch.mustReturn) {
  28442. return this;
  28443. }
  28444. // Checking geometry state
  28445. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28446. return this;
  28447. }
  28448. this.onBeforeRenderObservable.notifyObservers(this);
  28449. var engine = scene.getEngine();
  28450. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28451. // Material
  28452. var material = subMesh.getMaterial();
  28453. if (!material) {
  28454. return this;
  28455. }
  28456. this._effectiveMaterial = material;
  28457. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28458. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28459. return this;
  28460. }
  28461. }
  28462. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  28463. return this;
  28464. }
  28465. // Alpha mode
  28466. if (enableAlphaMode) {
  28467. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  28468. }
  28469. // Outline - step 1
  28470. var savedDepthWrite = engine.getDepthWrite();
  28471. if (this.renderOutline) {
  28472. engine.setDepthWrite(false);
  28473. scene.getOutlineRenderer().render(subMesh, batch);
  28474. engine.setDepthWrite(savedDepthWrite);
  28475. }
  28476. var effect;
  28477. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28478. effect = subMesh.effect;
  28479. }
  28480. else {
  28481. effect = this._effectiveMaterial.getEffect();
  28482. }
  28483. if (!effect) {
  28484. return this;
  28485. }
  28486. var sideOrientation = this.overrideMaterialSideOrientation;
  28487. if (sideOrientation == null) {
  28488. sideOrientation = this._effectiveMaterial.sideOrientation;
  28489. if (this._getWorldMatrixDeterminant() < 0) {
  28490. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  28491. }
  28492. }
  28493. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  28494. if (this._effectiveMaterial.forceDepthWrite) {
  28495. engine.setDepthWrite(true);
  28496. }
  28497. // Bind
  28498. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  28499. if (!hardwareInstancedRendering) {
  28500. this._bind(subMesh, effect, fillMode);
  28501. }
  28502. var world = this.getWorldMatrix();
  28503. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28504. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  28505. }
  28506. else {
  28507. this._effectiveMaterial.bind(world, this);
  28508. }
  28509. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  28510. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  28511. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28512. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  28513. }
  28514. // Draw
  28515. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28516. // Unbind
  28517. this._effectiveMaterial.unbind();
  28518. // Outline - step 2
  28519. if (this.renderOutline && savedDepthWrite) {
  28520. engine.setDepthWrite(true);
  28521. engine.setColorWrite(false);
  28522. scene.getOutlineRenderer().render(subMesh, batch);
  28523. engine.setColorWrite(true);
  28524. }
  28525. // Overlay
  28526. if (this.renderOverlay) {
  28527. var currentMode = engine.getAlphaMode();
  28528. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28529. scene.getOutlineRenderer().render(subMesh, batch, true);
  28530. engine.setAlphaMode(currentMode);
  28531. }
  28532. this.onAfterRenderObservable.notifyObservers(this);
  28533. return this;
  28534. };
  28535. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  28536. if (isInstance && effectiveMaterial) {
  28537. effectiveMaterial.bindOnlyWorldMatrix(world);
  28538. }
  28539. };
  28540. /**
  28541. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  28542. */
  28543. Mesh.prototype.getEmittedParticleSystems = function () {
  28544. var results = new Array();
  28545. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28546. var particleSystem = this.getScene().particleSystems[index];
  28547. if (particleSystem.emitter === this) {
  28548. results.push(particleSystem);
  28549. }
  28550. }
  28551. return results;
  28552. };
  28553. /**
  28554. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  28555. */
  28556. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  28557. var results = new Array();
  28558. var descendants = this.getDescendants();
  28559. descendants.push(this);
  28560. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28561. var particleSystem = this.getScene().particleSystems[index];
  28562. var emitter = particleSystem.emitter;
  28563. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  28564. results.push(particleSystem);
  28565. }
  28566. }
  28567. return results;
  28568. };
  28569. Mesh.prototype._checkDelayState = function () {
  28570. var scene = this.getScene();
  28571. if (this._geometry) {
  28572. this._geometry.load(scene);
  28573. }
  28574. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  28575. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28576. this._queueLoad(scene);
  28577. }
  28578. return this;
  28579. };
  28580. Mesh.prototype._queueLoad = function (scene) {
  28581. var _this = this;
  28582. scene._addPendingData(this);
  28583. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  28584. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28585. if (data instanceof ArrayBuffer) {
  28586. _this._delayLoadingFunction(data, _this);
  28587. }
  28588. else {
  28589. _this._delayLoadingFunction(JSON.parse(data), _this);
  28590. }
  28591. _this.instances.forEach(function (instance) {
  28592. instance._syncSubMeshes();
  28593. });
  28594. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28595. scene._removePendingData(_this);
  28596. }, function () { }, scene.database, getBinaryData);
  28597. return this;
  28598. };
  28599. /**
  28600. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  28601. */
  28602. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  28603. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28604. return false;
  28605. }
  28606. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  28607. return false;
  28608. }
  28609. this._checkDelayState();
  28610. return true;
  28611. };
  28612. /**
  28613. * Sets the mesh material by the material or multiMaterial `id` property.
  28614. * The material `id` is a string identifying the material or the multiMaterial.
  28615. * This method returns the Mesh.
  28616. */
  28617. Mesh.prototype.setMaterialByID = function (id) {
  28618. var materials = this.getScene().materials;
  28619. var index;
  28620. for (index = materials.length - 1; index > -1; index--) {
  28621. if (materials[index].id === id) {
  28622. this.material = materials[index];
  28623. return this;
  28624. }
  28625. }
  28626. // Multi
  28627. var multiMaterials = this.getScene().multiMaterials;
  28628. for (index = multiMaterials.length - 1; index > -1; index--) {
  28629. if (multiMaterials[index].id === id) {
  28630. this.material = multiMaterials[index];
  28631. return this;
  28632. }
  28633. }
  28634. return this;
  28635. };
  28636. /**
  28637. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  28638. */
  28639. Mesh.prototype.getAnimatables = function () {
  28640. var results = new Array();
  28641. if (this.material) {
  28642. results.push(this.material);
  28643. }
  28644. if (this.skeleton) {
  28645. results.push(this.skeleton);
  28646. }
  28647. return results;
  28648. };
  28649. /**
  28650. * Modifies the mesh geometry according to the passed transformation matrix.
  28651. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  28652. * The mesh normals are modified accordingly the same transformation.
  28653. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  28654. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28655. * Returns the Mesh.
  28656. */
  28657. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  28658. // Position
  28659. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28660. return this;
  28661. }
  28662. var submeshes = this.subMeshes.splice(0);
  28663. this._resetPointsArrayCache();
  28664. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28665. var temp = new Array();
  28666. var index;
  28667. for (index = 0; index < data.length; index += 3) {
  28668. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  28669. }
  28670. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  28671. // Normals
  28672. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28673. return this;
  28674. }
  28675. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28676. temp = [];
  28677. for (index = 0; index < data.length; index += 3) {
  28678. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  28679. }
  28680. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  28681. // flip faces?
  28682. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  28683. this.flipFaces();
  28684. }
  28685. // Restore submeshes
  28686. this.releaseSubMeshes();
  28687. this.subMeshes = submeshes;
  28688. return this;
  28689. };
  28690. /**
  28691. * Modifies the mesh geometry according to its own current World Matrix.
  28692. * The mesh World Matrix is then reset.
  28693. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  28694. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  28695. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28696. * Returns the Mesh.
  28697. */
  28698. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  28699. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  28700. this.scaling.copyFromFloats(1, 1, 1);
  28701. this.position.copyFromFloats(0, 0, 0);
  28702. this.rotation.copyFromFloats(0, 0, 0);
  28703. //only if quaternion is already set
  28704. if (this.rotationQuaternion) {
  28705. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  28706. }
  28707. this._worldMatrix = BABYLON.Matrix.Identity();
  28708. return this;
  28709. };
  28710. Object.defineProperty(Mesh.prototype, "_positions", {
  28711. // Cache
  28712. get: function () {
  28713. if (this._geometry) {
  28714. return this._geometry._positions;
  28715. }
  28716. return null;
  28717. },
  28718. enumerable: true,
  28719. configurable: true
  28720. });
  28721. Mesh.prototype._resetPointsArrayCache = function () {
  28722. if (this._geometry) {
  28723. this._geometry._resetPointsArrayCache();
  28724. }
  28725. return this;
  28726. };
  28727. Mesh.prototype._generatePointsArray = function () {
  28728. if (this._geometry) {
  28729. return this._geometry._generatePointsArray();
  28730. }
  28731. return false;
  28732. };
  28733. /**
  28734. * Returns a new Mesh object generated from the current mesh properties.
  28735. * This method must not get confused with createInstance().
  28736. * The parameter `name` is a string, the name given to the new mesh.
  28737. * The optional parameter `newParent` can be any Node object (default `null`).
  28738. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  28739. * 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.
  28740. */
  28741. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  28742. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  28743. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  28744. };
  28745. /**
  28746. * Disposes the Mesh.
  28747. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  28748. * Returns nothing.
  28749. */
  28750. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  28751. var _this = this;
  28752. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  28753. this.morphTargetManager = null;
  28754. if (this._geometry) {
  28755. this._geometry.releaseForMesh(this, true);
  28756. }
  28757. // Sources
  28758. var meshes = this.getScene().meshes;
  28759. meshes.forEach(function (abstractMesh) {
  28760. var mesh = abstractMesh;
  28761. if (mesh._source && mesh._source === _this) {
  28762. mesh._source = null;
  28763. }
  28764. });
  28765. this._source = null;
  28766. // Instances
  28767. if (this._instancesBuffer) {
  28768. this._instancesBuffer.dispose();
  28769. this._instancesBuffer = null;
  28770. }
  28771. while (this.instances.length) {
  28772. this.instances[0].dispose();
  28773. }
  28774. // Effect layers.
  28775. var effectLayers = this.getScene().effectLayers;
  28776. for (var i = 0; i < effectLayers.length; i++) {
  28777. var effectLayer = effectLayers[i];
  28778. if (effectLayer) {
  28779. effectLayer._disposeMesh(this);
  28780. }
  28781. }
  28782. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  28783. };
  28784. /**
  28785. * Modifies the mesh geometry according to a displacement map.
  28786. * 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.
  28787. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28788. * This method returns nothing.
  28789. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  28790. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28791. * 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.
  28792. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28793. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28794. *
  28795. * Returns the Mesh.
  28796. */
  28797. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  28798. var _this = this;
  28799. var scene = this.getScene();
  28800. var onload = function (img) {
  28801. // Getting height map data
  28802. var canvas = document.createElement("canvas");
  28803. var context = canvas.getContext("2d");
  28804. var heightMapWidth = img.width;
  28805. var heightMapHeight = img.height;
  28806. canvas.width = heightMapWidth;
  28807. canvas.height = heightMapHeight;
  28808. context.drawImage(img, 0, 0);
  28809. // Create VertexData from map data
  28810. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  28811. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  28812. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  28813. //execute success callback, if set
  28814. if (onSuccess) {
  28815. onSuccess(_this);
  28816. }
  28817. };
  28818. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  28819. return this;
  28820. };
  28821. /**
  28822. * Modifies the mesh geometry according to a displacementMap buffer.
  28823. * 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.
  28824. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28825. * This method returns nothing.
  28826. * 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.
  28827. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  28828. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28829. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28830. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28831. *
  28832. * Returns the Mesh.
  28833. */
  28834. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  28835. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  28836. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  28837. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28838. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  28839. return this;
  28840. }
  28841. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28842. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28843. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28844. var position = BABYLON.Vector3.Zero();
  28845. var normal = BABYLON.Vector3.Zero();
  28846. var uv = BABYLON.Vector2.Zero();
  28847. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  28848. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  28849. for (var index = 0; index < positions.length; index += 3) {
  28850. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  28851. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  28852. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  28853. // Compute height
  28854. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  28855. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  28856. var pos = (u + v * heightMapWidth) * 4;
  28857. var r = buffer[pos] / 255.0;
  28858. var g = buffer[pos + 1] / 255.0;
  28859. var b = buffer[pos + 2] / 255.0;
  28860. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28861. normal.normalize();
  28862. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  28863. position = position.add(normal);
  28864. position.toArray(positions, index);
  28865. }
  28866. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  28867. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  28868. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  28869. return this;
  28870. };
  28871. /**
  28872. * Modify the mesh to get a flat shading rendering.
  28873. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  28874. * This method returns the Mesh.
  28875. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  28876. */
  28877. Mesh.prototype.convertToFlatShadedMesh = function () {
  28878. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  28879. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28880. var kinds = this.getVerticesDataKinds();
  28881. var vbs = {};
  28882. var data = {};
  28883. var newdata = {};
  28884. var updatableNormals = false;
  28885. var kindIndex;
  28886. var kind;
  28887. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28888. kind = kinds[kindIndex];
  28889. var vertexBuffer = this.getVertexBuffer(kind);
  28890. if (kind === BABYLON.VertexBuffer.NormalKind) {
  28891. updatableNormals = vertexBuffer.isUpdatable();
  28892. kinds.splice(kindIndex, 1);
  28893. kindIndex--;
  28894. continue;
  28895. }
  28896. vbs[kind] = vertexBuffer;
  28897. data[kind] = vbs[kind].getData();
  28898. newdata[kind] = [];
  28899. }
  28900. // Save previous submeshes
  28901. var previousSubmeshes = this.subMeshes.slice(0);
  28902. var indices = this.getIndices();
  28903. var totalIndices = this.getTotalIndices();
  28904. // Generating unique vertices per face
  28905. var index;
  28906. for (index = 0; index < totalIndices; index++) {
  28907. var vertexIndex = indices[index];
  28908. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28909. kind = kinds[kindIndex];
  28910. var stride = vbs[kind].getStrideSize();
  28911. for (var offset = 0; offset < stride; offset++) {
  28912. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28913. }
  28914. }
  28915. }
  28916. // Updating faces & normal
  28917. var normals = [];
  28918. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  28919. for (index = 0; index < totalIndices; index += 3) {
  28920. indices[index] = index;
  28921. indices[index + 1] = index + 1;
  28922. indices[index + 2] = index + 2;
  28923. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  28924. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  28925. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  28926. var p1p2 = p1.subtract(p2);
  28927. var p3p2 = p3.subtract(p2);
  28928. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  28929. // Store same normals for every vertex
  28930. for (var localIndex = 0; localIndex < 3; localIndex++) {
  28931. normals.push(normal.x);
  28932. normals.push(normal.y);
  28933. normals.push(normal.z);
  28934. }
  28935. }
  28936. this.setIndices(indices);
  28937. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  28938. // Updating vertex buffers
  28939. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28940. kind = kinds[kindIndex];
  28941. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28942. }
  28943. // Updating submeshes
  28944. this.releaseSubMeshes();
  28945. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28946. var previousOne = previousSubmeshes[submeshIndex];
  28947. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28948. }
  28949. this.synchronizeInstances();
  28950. return this;
  28951. };
  28952. /**
  28953. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  28954. * In other words, more vertices, no more indices and a single bigger VBO.
  28955. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  28956. * Returns the Mesh.
  28957. */
  28958. Mesh.prototype.convertToUnIndexedMesh = function () {
  28959. /// <summary>Remove indices by unfolding faces into buffers</summary>
  28960. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28961. var kinds = this.getVerticesDataKinds();
  28962. var vbs = {};
  28963. var data = {};
  28964. var newdata = {};
  28965. var kindIndex;
  28966. var kind;
  28967. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28968. kind = kinds[kindIndex];
  28969. var vertexBuffer = this.getVertexBuffer(kind);
  28970. vbs[kind] = vertexBuffer;
  28971. data[kind] = vbs[kind].getData();
  28972. newdata[kind] = [];
  28973. }
  28974. // Save previous submeshes
  28975. var previousSubmeshes = this.subMeshes.slice(0);
  28976. var indices = this.getIndices();
  28977. var totalIndices = this.getTotalIndices();
  28978. // Generating unique vertices per face
  28979. var index;
  28980. for (index = 0; index < totalIndices; index++) {
  28981. var vertexIndex = indices[index];
  28982. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28983. kind = kinds[kindIndex];
  28984. var stride = vbs[kind].getStrideSize();
  28985. for (var offset = 0; offset < stride; offset++) {
  28986. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28987. }
  28988. }
  28989. }
  28990. // Updating indices
  28991. for (index = 0; index < totalIndices; index += 3) {
  28992. indices[index] = index;
  28993. indices[index + 1] = index + 1;
  28994. indices[index + 2] = index + 2;
  28995. }
  28996. this.setIndices(indices);
  28997. // Updating vertex buffers
  28998. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28999. kind = kinds[kindIndex];
  29000. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29001. }
  29002. // Updating submeshes
  29003. this.releaseSubMeshes();
  29004. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29005. var previousOne = previousSubmeshes[submeshIndex];
  29006. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29007. }
  29008. this._unIndexed = true;
  29009. this.synchronizeInstances();
  29010. return this;
  29011. };
  29012. /**
  29013. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  29014. * This method returns the Mesh.
  29015. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  29016. */
  29017. Mesh.prototype.flipFaces = function (flipNormals) {
  29018. if (flipNormals === void 0) { flipNormals = false; }
  29019. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  29020. var i;
  29021. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  29022. for (i = 0; i < vertex_data.normals.length; i++) {
  29023. vertex_data.normals[i] *= -1;
  29024. }
  29025. }
  29026. if (vertex_data.indices) {
  29027. var temp;
  29028. for (i = 0; i < vertex_data.indices.length; i += 3) {
  29029. // reassign indices
  29030. temp = vertex_data.indices[i + 1];
  29031. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  29032. vertex_data.indices[i + 2] = temp;
  29033. }
  29034. }
  29035. vertex_data.applyToMesh(this);
  29036. return this;
  29037. };
  29038. // Instances
  29039. /**
  29040. * Creates a new InstancedMesh object from the mesh model.
  29041. * An instance shares the same properties and the same material than its model.
  29042. * Only these properties of each instance can then be set individually :
  29043. * - position
  29044. * - rotation
  29045. * - rotationQuaternion
  29046. * - setPivotMatrix
  29047. * - scaling
  29048. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  29049. * Warning : this method is not supported for Line mesh and LineSystem
  29050. */
  29051. Mesh.prototype.createInstance = function (name) {
  29052. return new BABYLON.InstancedMesh(name, this);
  29053. };
  29054. /**
  29055. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  29056. * After this call, all the mesh instances have the same submeshes than the current mesh.
  29057. * This method returns the Mesh.
  29058. */
  29059. Mesh.prototype.synchronizeInstances = function () {
  29060. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  29061. var instance = this.instances[instanceIndex];
  29062. instance._syncSubMeshes();
  29063. }
  29064. return this;
  29065. };
  29066. /**
  29067. * Simplify the mesh according to the given array of settings.
  29068. * Function will return immediately and will simplify async. It returns the Mesh.
  29069. * @param settings a collection of simplification settings.
  29070. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29071. * @param type the type of simplification to run.
  29072. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29073. */
  29074. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29075. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29076. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29077. this.getScene().simplificationQueue.addTask({
  29078. settings: settings,
  29079. parallelProcessing: parallelProcessing,
  29080. mesh: this,
  29081. simplificationType: simplificationType,
  29082. successCallback: successCallback
  29083. });
  29084. return this;
  29085. };
  29086. /**
  29087. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29088. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29089. * This should be used together with the simplification to avoid disappearing triangles.
  29090. * Returns the Mesh.
  29091. * @param successCallback an optional success callback to be called after the optimization finished.
  29092. */
  29093. Mesh.prototype.optimizeIndices = function (successCallback) {
  29094. var _this = this;
  29095. var indices = this.getIndices();
  29096. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29097. if (!positions || !indices) {
  29098. return this;
  29099. }
  29100. var vectorPositions = new Array();
  29101. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29102. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29103. }
  29104. var dupes = new Array();
  29105. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29106. var realPos = vectorPositions.length - 1 - iteration;
  29107. var testedPosition = vectorPositions[realPos];
  29108. for (var j = 0; j < realPos; ++j) {
  29109. var againstPosition = vectorPositions[j];
  29110. if (testedPosition.equals(againstPosition)) {
  29111. dupes[realPos] = j;
  29112. break;
  29113. }
  29114. }
  29115. }, function () {
  29116. for (var i = 0; i < indices.length; ++i) {
  29117. indices[i] = dupes[indices[i]] || indices[i];
  29118. }
  29119. //indices are now reordered
  29120. var originalSubMeshes = _this.subMeshes.slice(0);
  29121. _this.setIndices(indices);
  29122. _this.subMeshes = originalSubMeshes;
  29123. if (successCallback) {
  29124. successCallback(_this);
  29125. }
  29126. });
  29127. return this;
  29128. };
  29129. Mesh.prototype.serialize = function (serializationObject) {
  29130. serializationObject.name = this.name;
  29131. serializationObject.id = this.id;
  29132. serializationObject.type = this.getClassName();
  29133. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29134. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29135. }
  29136. serializationObject.position = this.position.asArray();
  29137. if (this.rotationQuaternion) {
  29138. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29139. }
  29140. else if (this.rotation) {
  29141. serializationObject.rotation = this.rotation.asArray();
  29142. }
  29143. serializationObject.scaling = this.scaling.asArray();
  29144. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29145. serializationObject.isEnabled = this.isEnabled(false);
  29146. serializationObject.isVisible = this.isVisible;
  29147. serializationObject.infiniteDistance = this.infiniteDistance;
  29148. serializationObject.pickable = this.isPickable;
  29149. serializationObject.receiveShadows = this.receiveShadows;
  29150. serializationObject.billboardMode = this.billboardMode;
  29151. serializationObject.visibility = this.visibility;
  29152. serializationObject.checkCollisions = this.checkCollisions;
  29153. serializationObject.isBlocker = this.isBlocker;
  29154. // Parent
  29155. if (this.parent) {
  29156. serializationObject.parentId = this.parent.id;
  29157. }
  29158. // Geometry
  29159. serializationObject.isUnIndexed = this.isUnIndexed;
  29160. var geometry = this._geometry;
  29161. if (geometry) {
  29162. var geometryId = geometry.id;
  29163. serializationObject.geometryId = geometryId;
  29164. // SubMeshes
  29165. serializationObject.subMeshes = [];
  29166. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29167. var subMesh = this.subMeshes[subIndex];
  29168. serializationObject.subMeshes.push({
  29169. materialIndex: subMesh.materialIndex,
  29170. verticesStart: subMesh.verticesStart,
  29171. verticesCount: subMesh.verticesCount,
  29172. indexStart: subMesh.indexStart,
  29173. indexCount: subMesh.indexCount
  29174. });
  29175. }
  29176. }
  29177. // Material
  29178. if (this.material) {
  29179. serializationObject.materialId = this.material.id;
  29180. }
  29181. else {
  29182. this.material = null;
  29183. }
  29184. // Morph targets
  29185. if (this.morphTargetManager) {
  29186. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29187. }
  29188. // Skeleton
  29189. if (this.skeleton) {
  29190. serializationObject.skeletonId = this.skeleton.id;
  29191. }
  29192. // Physics
  29193. //TODO implement correct serialization for physics impostors.
  29194. var impostor = this.getPhysicsImpostor();
  29195. if (impostor) {
  29196. serializationObject.physicsMass = impostor.getParam("mass");
  29197. serializationObject.physicsFriction = impostor.getParam("friction");
  29198. serializationObject.physicsRestitution = impostor.getParam("mass");
  29199. serializationObject.physicsImpostor = impostor.type;
  29200. }
  29201. // Metadata
  29202. if (this.metadata) {
  29203. serializationObject.metadata = this.metadata;
  29204. }
  29205. // Instances
  29206. serializationObject.instances = [];
  29207. for (var index = 0; index < this.instances.length; index++) {
  29208. var instance = this.instances[index];
  29209. var serializationInstance = {
  29210. name: instance.name,
  29211. id: instance.id,
  29212. position: instance.position.asArray(),
  29213. scaling: instance.scaling.asArray()
  29214. };
  29215. if (instance.rotationQuaternion) {
  29216. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29217. }
  29218. else if (instance.rotation) {
  29219. serializationInstance.rotation = instance.rotation.asArray();
  29220. }
  29221. serializationObject.instances.push(serializationInstance);
  29222. // Animations
  29223. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29224. serializationInstance.ranges = instance.serializeAnimationRanges();
  29225. }
  29226. //
  29227. // Animations
  29228. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29229. serializationObject.ranges = this.serializeAnimationRanges();
  29230. // Layer mask
  29231. serializationObject.layerMask = this.layerMask;
  29232. // Alpha
  29233. serializationObject.alphaIndex = this.alphaIndex;
  29234. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29235. // Overlay
  29236. serializationObject.overlayAlpha = this.overlayAlpha;
  29237. serializationObject.overlayColor = this.overlayColor.asArray();
  29238. serializationObject.renderOverlay = this.renderOverlay;
  29239. // Fog
  29240. serializationObject.applyFog = this.applyFog;
  29241. // Action Manager
  29242. if (this.actionManager) {
  29243. serializationObject.actions = this.actionManager.serialize(this.name);
  29244. }
  29245. };
  29246. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29247. if (!this.geometry) {
  29248. return;
  29249. }
  29250. this._markSubMeshesAsAttributesDirty();
  29251. var morphTargetManager = this._morphTargetManager;
  29252. if (morphTargetManager && morphTargetManager.vertexCount) {
  29253. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29254. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29255. this.morphTargetManager = null;
  29256. return;
  29257. }
  29258. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29259. var morphTarget = morphTargetManager.getActiveTarget(index);
  29260. var positions = morphTarget.getPositions();
  29261. if (!positions) {
  29262. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29263. return;
  29264. }
  29265. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29266. var normals = morphTarget.getNormals();
  29267. if (normals) {
  29268. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29269. }
  29270. var tangents = morphTarget.getTangents();
  29271. if (tangents) {
  29272. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29273. }
  29274. }
  29275. }
  29276. else {
  29277. var index = 0;
  29278. // Positions
  29279. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29280. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29281. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29282. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29283. }
  29284. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29285. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29286. }
  29287. index++;
  29288. }
  29289. }
  29290. };
  29291. // Statics
  29292. /**
  29293. * Returns a new Mesh object parsed from the source provided.
  29294. * The parameter `parsedMesh` is the source.
  29295. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29296. */
  29297. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29298. var mesh;
  29299. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29300. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29301. }
  29302. else {
  29303. mesh = new Mesh(parsedMesh.name, scene);
  29304. }
  29305. mesh.id = parsedMesh.id;
  29306. if (BABYLON.Tags) {
  29307. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29308. }
  29309. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29310. if (parsedMesh.metadata !== undefined) {
  29311. mesh.metadata = parsedMesh.metadata;
  29312. }
  29313. if (parsedMesh.rotationQuaternion) {
  29314. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29315. }
  29316. else if (parsedMesh.rotation) {
  29317. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29318. }
  29319. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29320. if (parsedMesh.localMatrix) {
  29321. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29322. }
  29323. else if (parsedMesh.pivotMatrix) {
  29324. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29325. }
  29326. mesh.setEnabled(parsedMesh.isEnabled);
  29327. mesh.isVisible = parsedMesh.isVisible;
  29328. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29329. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29330. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29331. if (parsedMesh.applyFog !== undefined) {
  29332. mesh.applyFog = parsedMesh.applyFog;
  29333. }
  29334. if (parsedMesh.pickable !== undefined) {
  29335. mesh.isPickable = parsedMesh.pickable;
  29336. }
  29337. if (parsedMesh.alphaIndex !== undefined) {
  29338. mesh.alphaIndex = parsedMesh.alphaIndex;
  29339. }
  29340. mesh.receiveShadows = parsedMesh.receiveShadows;
  29341. mesh.billboardMode = parsedMesh.billboardMode;
  29342. if (parsedMesh.visibility !== undefined) {
  29343. mesh.visibility = parsedMesh.visibility;
  29344. }
  29345. mesh.checkCollisions = parsedMesh.checkCollisions;
  29346. if (parsedMesh.isBlocker !== undefined) {
  29347. mesh.isBlocker = parsedMesh.isBlocker;
  29348. }
  29349. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29350. // freezeWorldMatrix
  29351. if (parsedMesh.freezeWorldMatrix) {
  29352. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29353. }
  29354. // Parent
  29355. if (parsedMesh.parentId) {
  29356. mesh._waitingParentId = parsedMesh.parentId;
  29357. }
  29358. // Actions
  29359. if (parsedMesh.actions !== undefined) {
  29360. mesh._waitingActions = parsedMesh.actions;
  29361. }
  29362. // Overlay
  29363. if (parsedMesh.overlayAlpha !== undefined) {
  29364. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29365. }
  29366. if (parsedMesh.overlayColor !== undefined) {
  29367. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29368. }
  29369. if (parsedMesh.renderOverlay !== undefined) {
  29370. mesh.renderOverlay = parsedMesh.renderOverlay;
  29371. }
  29372. // Geometry
  29373. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29374. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29375. if (parsedMesh.delayLoadingFile) {
  29376. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29377. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29378. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29379. if (parsedMesh._binaryInfo) {
  29380. mesh._binaryInfo = parsedMesh._binaryInfo;
  29381. }
  29382. mesh._delayInfo = [];
  29383. if (parsedMesh.hasUVs) {
  29384. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29385. }
  29386. if (parsedMesh.hasUVs2) {
  29387. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29388. }
  29389. if (parsedMesh.hasUVs3) {
  29390. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29391. }
  29392. if (parsedMesh.hasUVs4) {
  29393. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29394. }
  29395. if (parsedMesh.hasUVs5) {
  29396. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29397. }
  29398. if (parsedMesh.hasUVs6) {
  29399. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29400. }
  29401. if (parsedMesh.hasColors) {
  29402. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29403. }
  29404. if (parsedMesh.hasMatricesIndices) {
  29405. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29406. }
  29407. if (parsedMesh.hasMatricesWeights) {
  29408. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29409. }
  29410. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29411. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29412. mesh._checkDelayState();
  29413. }
  29414. }
  29415. else {
  29416. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29417. }
  29418. // Material
  29419. if (parsedMesh.materialId) {
  29420. mesh.setMaterialByID(parsedMesh.materialId);
  29421. }
  29422. else {
  29423. mesh.material = null;
  29424. }
  29425. // Morph targets
  29426. if (parsedMesh.morphTargetManagerId > -1) {
  29427. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29428. }
  29429. // Skeleton
  29430. if (parsedMesh.skeletonId > -1) {
  29431. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29432. if (parsedMesh.numBoneInfluencers) {
  29433. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29434. }
  29435. }
  29436. // Animations
  29437. if (parsedMesh.animations) {
  29438. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29439. var parsedAnimation = parsedMesh.animations[animationIndex];
  29440. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29441. }
  29442. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29443. }
  29444. if (parsedMesh.autoAnimate) {
  29445. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29446. }
  29447. // Layer Mask
  29448. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29449. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29450. }
  29451. else {
  29452. mesh.layerMask = 0x0FFFFFFF;
  29453. }
  29454. // Physics
  29455. if (parsedMesh.physicsImpostor) {
  29456. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29457. mass: parsedMesh.physicsMass,
  29458. friction: parsedMesh.physicsFriction,
  29459. restitution: parsedMesh.physicsRestitution
  29460. }, scene);
  29461. }
  29462. // Instances
  29463. if (parsedMesh.instances) {
  29464. for (var index = 0; index < parsedMesh.instances.length; index++) {
  29465. var parsedInstance = parsedMesh.instances[index];
  29466. var instance = mesh.createInstance(parsedInstance.name);
  29467. if (parsedInstance.id) {
  29468. instance.id = parsedInstance.id;
  29469. }
  29470. if (BABYLON.Tags) {
  29471. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  29472. }
  29473. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  29474. if (parsedInstance.parentId) {
  29475. instance._waitingParentId = parsedInstance.parentId;
  29476. }
  29477. if (parsedInstance.rotationQuaternion) {
  29478. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  29479. }
  29480. else if (parsedInstance.rotation) {
  29481. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  29482. }
  29483. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  29484. instance.checkCollisions = mesh.checkCollisions;
  29485. if (parsedMesh.animations) {
  29486. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29487. parsedAnimation = parsedMesh.animations[animationIndex];
  29488. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29489. }
  29490. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  29491. }
  29492. }
  29493. }
  29494. return mesh;
  29495. };
  29496. /**
  29497. * Creates a ribbon mesh.
  29498. * Please consider using the same method from the MeshBuilder class instead.
  29499. * 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.
  29500. *
  29501. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  29502. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  29503. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  29504. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  29505. * 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.
  29506. * 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.
  29507. * 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
  29508. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29509. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29510. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29511. */
  29512. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  29513. if (closeArray === void 0) { closeArray = false; }
  29514. if (updatable === void 0) { updatable = false; }
  29515. return BABYLON.MeshBuilder.CreateRibbon(name, {
  29516. pathArray: pathArray,
  29517. closeArray: closeArray,
  29518. closePath: closePath,
  29519. offset: offset,
  29520. updatable: updatable,
  29521. sideOrientation: sideOrientation,
  29522. instance: instance
  29523. }, scene);
  29524. };
  29525. /**
  29526. * Creates a plane polygonal mesh. By default, this is a disc.
  29527. * Please consider using the same method from the MeshBuilder class instead.
  29528. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  29529. * 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.
  29530. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29531. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29532. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29533. */
  29534. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  29535. if (scene === void 0) { scene = null; }
  29536. var options = {
  29537. radius: radius,
  29538. tessellation: tessellation,
  29539. sideOrientation: sideOrientation,
  29540. updatable: updatable
  29541. };
  29542. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  29543. };
  29544. /**
  29545. * Creates a box mesh.
  29546. * Please consider using the same method from the MeshBuilder class instead.
  29547. * The parameter `size` sets the size (float) of each box side (default 1).
  29548. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29549. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29550. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29551. */
  29552. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  29553. if (scene === void 0) { scene = null; }
  29554. var options = {
  29555. size: size,
  29556. sideOrientation: sideOrientation,
  29557. updatable: updatable
  29558. };
  29559. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  29560. };
  29561. /**
  29562. * Creates a sphere mesh.
  29563. * Please consider using the same method from the MeshBuilder class instead.
  29564. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  29565. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  29566. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29567. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29568. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29569. */
  29570. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  29571. var options = {
  29572. segments: segments,
  29573. diameterX: diameter,
  29574. diameterY: diameter,
  29575. diameterZ: diameter,
  29576. sideOrientation: sideOrientation,
  29577. updatable: updatable
  29578. };
  29579. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  29580. };
  29581. /**
  29582. * Creates a cylinder or a cone mesh.
  29583. * Please consider using the same method from the MeshBuilder class instead.
  29584. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  29585. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  29586. * 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.
  29587. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  29588. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  29589. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29590. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29591. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29592. */
  29593. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  29594. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  29595. if (scene !== undefined) {
  29596. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  29597. updatable = scene;
  29598. }
  29599. scene = subdivisions;
  29600. subdivisions = 1;
  29601. }
  29602. var options = {
  29603. height: height,
  29604. diameterTop: diameterTop,
  29605. diameterBottom: diameterBottom,
  29606. tessellation: tessellation,
  29607. subdivisions: subdivisions,
  29608. sideOrientation: sideOrientation,
  29609. updatable: updatable
  29610. };
  29611. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  29612. };
  29613. // Torus (Code from SharpDX.org)
  29614. /**
  29615. * Creates a torus mesh.
  29616. * Please consider using the same method from the MeshBuilder class instead.
  29617. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  29618. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  29619. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  29620. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29621. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29622. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29623. */
  29624. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  29625. var options = {
  29626. diameter: diameter,
  29627. thickness: thickness,
  29628. tessellation: tessellation,
  29629. sideOrientation: sideOrientation,
  29630. updatable: updatable
  29631. };
  29632. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  29633. };
  29634. /**
  29635. * Creates a torus knot mesh.
  29636. * Please consider using the same method from the MeshBuilder class instead.
  29637. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  29638. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  29639. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  29640. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  29641. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29642. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29643. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29644. */
  29645. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  29646. var options = {
  29647. radius: radius,
  29648. tube: tube,
  29649. radialSegments: radialSegments,
  29650. tubularSegments: tubularSegments,
  29651. p: p,
  29652. q: q,
  29653. sideOrientation: sideOrientation,
  29654. updatable: updatable
  29655. };
  29656. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  29657. };
  29658. /**
  29659. * Creates a line mesh.
  29660. * Please consider using the same method from the MeshBuilder class instead.
  29661. * 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.
  29662. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29663. * The parameter `points` is an array successive Vector3.
  29664. * 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
  29665. * When updating an instance, remember that only point positions can change, not the number of points.
  29666. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29667. */
  29668. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  29669. if (scene === void 0) { scene = null; }
  29670. if (updatable === void 0) { updatable = false; }
  29671. if (instance === void 0) { instance = null; }
  29672. var options = {
  29673. points: points,
  29674. updatable: updatable,
  29675. instance: instance
  29676. };
  29677. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  29678. };
  29679. /**
  29680. * Creates a dashed line mesh.
  29681. * Please consider using the same method from the MeshBuilder class instead.
  29682. * 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.
  29683. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29684. * The parameter `points` is an array successive Vector3.
  29685. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  29686. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  29687. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  29688. * 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
  29689. * When updating an instance, remember that only point positions can change, not the number of points.
  29690. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29691. */
  29692. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  29693. if (scene === void 0) { scene = null; }
  29694. var options = {
  29695. points: points,
  29696. dashSize: dashSize,
  29697. gapSize: gapSize,
  29698. dashNb: dashNb,
  29699. updatable: updatable,
  29700. instance: instance
  29701. };
  29702. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  29703. };
  29704. /**
  29705. * Creates a polygon mesh.
  29706. * Please consider using the same method from the MeshBuilder class instead.
  29707. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29708. * 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.
  29709. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29710. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29711. * Remember you can only change the shape positions, not their number when updating a polygon.
  29712. */
  29713. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  29714. var options = {
  29715. shape: shape,
  29716. holes: holes,
  29717. updatable: updatable,
  29718. sideOrientation: sideOrientation
  29719. };
  29720. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  29721. };
  29722. /**
  29723. * Creates an extruded polygon mesh, with depth in the Y direction.
  29724. * Please consider using the same method from the MeshBuilder class instead.
  29725. */
  29726. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  29727. var options = {
  29728. shape: shape,
  29729. holes: holes,
  29730. depth: depth,
  29731. updatable: updatable,
  29732. sideOrientation: sideOrientation
  29733. };
  29734. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  29735. };
  29736. /**
  29737. * Creates an extruded shape mesh.
  29738. * 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.
  29739. * Please consider using the same method from the MeshBuilder class instead.
  29740. *
  29741. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29742. * 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
  29743. * extruded along the Z axis.
  29744. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29745. * 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.
  29746. * The parameter `scale` (float, default 1) is the value to scale the shape.
  29747. * 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
  29748. * 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
  29749. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29750. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29751. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29752. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29753. */
  29754. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  29755. if (scene === void 0) { scene = null; }
  29756. var options = {
  29757. shape: shape,
  29758. path: path,
  29759. scale: scale,
  29760. rotation: rotation,
  29761. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29762. sideOrientation: sideOrientation,
  29763. instance: instance,
  29764. updatable: updatable
  29765. };
  29766. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  29767. };
  29768. /**
  29769. * Creates an custom extruded shape mesh.
  29770. * 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.
  29771. * Please consider using the same method from the MeshBuilder class instead.
  29772. *
  29773. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29774. * 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
  29775. * extruded along the Z axis.
  29776. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29777. * 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
  29778. * and the distance of this point from the begining of the path :
  29779. * ```javascript
  29780. * var rotationFunction = function(i, distance) {
  29781. * // do things
  29782. * return rotationValue; }
  29783. * ```
  29784. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  29785. * 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
  29786. * and the distance of this point from the begining of the path :
  29787. * ```javascript
  29788. * var scaleFunction = function(i, distance) {
  29789. * // do things
  29790. * return scaleValue;}
  29791. * ```
  29792. * It must returns a float value that will be the scale value applied to the shape on each path point.
  29793. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  29794. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  29795. * 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
  29796. * 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
  29797. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29798. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29799. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29800. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29801. */
  29802. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  29803. var options = {
  29804. shape: shape,
  29805. path: path,
  29806. scaleFunction: scaleFunction,
  29807. rotationFunction: rotationFunction,
  29808. ribbonCloseArray: ribbonCloseArray,
  29809. ribbonClosePath: ribbonClosePath,
  29810. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29811. sideOrientation: sideOrientation,
  29812. instance: instance,
  29813. updatable: updatable
  29814. };
  29815. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  29816. };
  29817. /**
  29818. * Creates lathe mesh.
  29819. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  29820. * Please consider using the same method from the MeshBuilder class instead.
  29821. * 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
  29822. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  29823. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  29824. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  29825. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29826. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29827. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29828. */
  29829. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  29830. var options = {
  29831. shape: shape,
  29832. radius: radius,
  29833. tessellation: tessellation,
  29834. sideOrientation: sideOrientation,
  29835. updatable: updatable
  29836. };
  29837. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  29838. };
  29839. /**
  29840. * Creates a plane mesh.
  29841. * Please consider using the same method from the MeshBuilder class instead.
  29842. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  29843. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29844. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29845. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29846. */
  29847. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  29848. var options = {
  29849. size: size,
  29850. width: size,
  29851. height: size,
  29852. sideOrientation: sideOrientation,
  29853. updatable: updatable
  29854. };
  29855. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  29856. };
  29857. /**
  29858. * Creates a ground mesh.
  29859. * Please consider using the same method from the MeshBuilder class instead.
  29860. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  29861. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  29862. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29863. */
  29864. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  29865. var options = {
  29866. width: width,
  29867. height: height,
  29868. subdivisions: subdivisions,
  29869. updatable: updatable
  29870. };
  29871. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  29872. };
  29873. /**
  29874. * Creates a tiled ground mesh.
  29875. * Please consider using the same method from the MeshBuilder class instead.
  29876. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  29877. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  29878. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  29879. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  29880. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  29881. * numbers of subdivisions on the ground width and height of each tile.
  29882. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29883. */
  29884. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  29885. var options = {
  29886. xmin: xmin,
  29887. zmin: zmin,
  29888. xmax: xmax,
  29889. zmax: zmax,
  29890. subdivisions: subdivisions,
  29891. precision: precision,
  29892. updatable: updatable
  29893. };
  29894. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  29895. };
  29896. /**
  29897. * Creates a ground mesh from a height map.
  29898. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  29899. * Please consider using the same method from the MeshBuilder class instead.
  29900. * The parameter `url` sets the URL of the height map image resource.
  29901. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  29902. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  29903. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  29904. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  29905. * 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).
  29906. * This function is passed the newly built mesh :
  29907. * ```javascript
  29908. * function(mesh) { // do things
  29909. * return; }
  29910. * ```
  29911. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29912. */
  29913. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  29914. var options = {
  29915. width: width,
  29916. height: height,
  29917. subdivisions: subdivisions,
  29918. minHeight: minHeight,
  29919. maxHeight: maxHeight,
  29920. updatable: updatable,
  29921. onReady: onReady
  29922. };
  29923. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  29924. };
  29925. /**
  29926. * Creates a tube mesh.
  29927. * 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.
  29928. * Please consider using the same method from the MeshBuilder class instead.
  29929. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  29930. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  29931. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  29932. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  29933. * 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.
  29934. * It must return a radius value (positive float) :
  29935. * ```javascript
  29936. * var radiusFunction = function(i, distance) {
  29937. * // do things
  29938. * return radius; }
  29939. * ```
  29940. * 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
  29941. * 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
  29942. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29943. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29944. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29945. */
  29946. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  29947. var options = {
  29948. path: path,
  29949. radius: radius,
  29950. tessellation: tessellation,
  29951. radiusFunction: radiusFunction,
  29952. arc: 1,
  29953. cap: cap,
  29954. updatable: updatable,
  29955. sideOrientation: sideOrientation,
  29956. instance: instance
  29957. };
  29958. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  29959. };
  29960. /**
  29961. * Creates a polyhedron mesh.
  29962. * Please consider using the same method from the MeshBuilder class instead.
  29963. * 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
  29964. * to choose the wanted type.
  29965. * The parameter `size` (positive float, default 1) sets the polygon size.
  29966. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  29967. * 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`.
  29968. * 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
  29969. * 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)`).
  29970. * 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
  29971. * 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.
  29972. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29973. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29974. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29975. */
  29976. Mesh.CreatePolyhedron = function (name, options, scene) {
  29977. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  29978. };
  29979. /**
  29980. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  29981. * Please consider using the same method from the MeshBuilder class instead.
  29982. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  29983. * 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`).
  29984. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  29985. * 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.
  29986. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29987. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29988. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29989. */
  29990. Mesh.CreateIcoSphere = function (name, options, scene) {
  29991. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  29992. };
  29993. /**
  29994. * Creates a decal mesh.
  29995. * Please consider using the same method from the MeshBuilder class instead.
  29996. * 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.
  29997. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  29998. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  29999. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  30000. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  30001. */
  30002. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  30003. var options = {
  30004. position: position,
  30005. normal: normal,
  30006. size: size,
  30007. angle: angle
  30008. };
  30009. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  30010. };
  30011. // Skeletons
  30012. /**
  30013. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30014. */
  30015. Mesh.prototype.setPositionsForCPUSkinning = function () {
  30016. if (!this._sourcePositions) {
  30017. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30018. if (!source) {
  30019. return this._sourcePositions;
  30020. }
  30021. this._sourcePositions = new Float32Array(source);
  30022. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30023. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  30024. }
  30025. }
  30026. return this._sourcePositions;
  30027. };
  30028. /**
  30029. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30030. */
  30031. Mesh.prototype.setNormalsForCPUSkinning = function () {
  30032. if (!this._sourceNormals) {
  30033. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30034. if (!source) {
  30035. return this._sourceNormals;
  30036. }
  30037. this._sourceNormals = new Float32Array(source);
  30038. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30039. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  30040. }
  30041. }
  30042. return this._sourceNormals;
  30043. };
  30044. /**
  30045. * Updates the vertex buffer by applying transformation from the bones.
  30046. * Returns the Mesh.
  30047. *
  30048. * @param {skeleton} skeleton to apply
  30049. */
  30050. Mesh.prototype.applySkeleton = function (skeleton) {
  30051. if (!this.geometry) {
  30052. return this;
  30053. }
  30054. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  30055. return this;
  30056. }
  30057. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  30058. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30059. return this;
  30060. }
  30061. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30062. return this;
  30063. }
  30064. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30065. return this;
  30066. }
  30067. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30068. return this;
  30069. }
  30070. if (!this._sourcePositions) {
  30071. var submeshes = this.subMeshes.slice();
  30072. this.setPositionsForCPUSkinning();
  30073. this.subMeshes = submeshes;
  30074. }
  30075. if (!this._sourceNormals) {
  30076. this.setNormalsForCPUSkinning();
  30077. }
  30078. // positionsData checks for not being Float32Array will only pass at most once
  30079. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30080. if (!positionsData) {
  30081. return this;
  30082. }
  30083. if (!(positionsData instanceof Float32Array)) {
  30084. positionsData = new Float32Array(positionsData);
  30085. }
  30086. // normalsData checks for not being Float32Array will only pass at most once
  30087. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30088. if (!normalsData) {
  30089. return this;
  30090. }
  30091. if (!(normalsData instanceof Float32Array)) {
  30092. normalsData = new Float32Array(normalsData);
  30093. }
  30094. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30095. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30096. if (!matricesWeightsData || !matricesIndicesData) {
  30097. return this;
  30098. }
  30099. var needExtras = this.numBoneInfluencers > 4;
  30100. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30101. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30102. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30103. var tempVector3 = BABYLON.Vector3.Zero();
  30104. var finalMatrix = new BABYLON.Matrix();
  30105. var tempMatrix = new BABYLON.Matrix();
  30106. var matWeightIdx = 0;
  30107. var inf;
  30108. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30109. var weight;
  30110. for (inf = 0; inf < 4; inf++) {
  30111. weight = matricesWeightsData[matWeightIdx + inf];
  30112. if (weight > 0) {
  30113. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30114. finalMatrix.addToSelf(tempMatrix);
  30115. }
  30116. else
  30117. break;
  30118. }
  30119. if (needExtras) {
  30120. for (inf = 0; inf < 4; inf++) {
  30121. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30122. if (weight > 0) {
  30123. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30124. finalMatrix.addToSelf(tempMatrix);
  30125. }
  30126. else
  30127. break;
  30128. }
  30129. }
  30130. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30131. tempVector3.toArray(positionsData, index);
  30132. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30133. tempVector3.toArray(normalsData, index);
  30134. finalMatrix.reset();
  30135. }
  30136. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30137. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30138. return this;
  30139. };
  30140. // Tools
  30141. /**
  30142. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30143. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30144. */
  30145. Mesh.MinMax = function (meshes) {
  30146. var minVector = null;
  30147. var maxVector = null;
  30148. meshes.forEach(function (mesh, index, array) {
  30149. var boundingInfo = mesh.getBoundingInfo();
  30150. var boundingBox = boundingInfo.boundingBox;
  30151. if (!minVector || !maxVector) {
  30152. minVector = boundingBox.minimumWorld;
  30153. maxVector = boundingBox.maximumWorld;
  30154. }
  30155. else {
  30156. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30157. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30158. }
  30159. });
  30160. if (!minVector || !maxVector) {
  30161. return {
  30162. min: BABYLON.Vector3.Zero(),
  30163. max: BABYLON.Vector3.Zero()
  30164. };
  30165. }
  30166. return {
  30167. min: minVector,
  30168. max: maxVector
  30169. };
  30170. };
  30171. /**
  30172. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30173. */
  30174. Mesh.Center = function (meshesOrMinMaxVector) {
  30175. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30176. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30177. };
  30178. /**
  30179. * Merge the array of meshes into a single mesh for performance reasons.
  30180. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30181. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30182. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30183. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30184. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30185. */
  30186. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30187. if (disposeSource === void 0) { disposeSource = true; }
  30188. var index;
  30189. if (!allow32BitsIndices) {
  30190. var totalVertices = 0;
  30191. // Counting vertices
  30192. for (index = 0; index < meshes.length; index++) {
  30193. if (meshes[index]) {
  30194. totalVertices += meshes[index].getTotalVertices();
  30195. if (totalVertices > 65536) {
  30196. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30197. return null;
  30198. }
  30199. }
  30200. }
  30201. }
  30202. // Merge
  30203. var vertexData = null;
  30204. var otherVertexData;
  30205. var indiceArray = new Array();
  30206. var source = null;
  30207. for (index = 0; index < meshes.length; index++) {
  30208. if (meshes[index]) {
  30209. meshes[index].computeWorldMatrix(true);
  30210. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30211. otherVertexData.transform(meshes[index].getWorldMatrix());
  30212. if (vertexData) {
  30213. vertexData.merge(otherVertexData);
  30214. }
  30215. else {
  30216. vertexData = otherVertexData;
  30217. source = meshes[index];
  30218. }
  30219. if (subdivideWithSubMeshes) {
  30220. indiceArray.push(meshes[index].getTotalIndices());
  30221. }
  30222. }
  30223. }
  30224. source = source;
  30225. if (!meshSubclass) {
  30226. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30227. }
  30228. vertexData.applyToMesh(meshSubclass);
  30229. // Setting properties
  30230. meshSubclass.material = source.material;
  30231. meshSubclass.checkCollisions = source.checkCollisions;
  30232. // Cleaning
  30233. if (disposeSource) {
  30234. for (index = 0; index < meshes.length; index++) {
  30235. if (meshes[index]) {
  30236. meshes[index].dispose();
  30237. }
  30238. }
  30239. }
  30240. // Subdivide
  30241. if (subdivideWithSubMeshes) {
  30242. //-- Suppresions du submesh global
  30243. meshSubclass.releaseSubMeshes();
  30244. index = 0;
  30245. var offset = 0;
  30246. //-- aplique la subdivision en fonction du tableau d'indices
  30247. while (index < indiceArray.length) {
  30248. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30249. offset += indiceArray[index];
  30250. index++;
  30251. }
  30252. }
  30253. return meshSubclass;
  30254. };
  30255. // Consts
  30256. Mesh._FRONTSIDE = 0;
  30257. Mesh._BACKSIDE = 1;
  30258. Mesh._DOUBLESIDE = 2;
  30259. Mesh._DEFAULTSIDE = 0;
  30260. Mesh._NO_CAP = 0;
  30261. Mesh._CAP_START = 1;
  30262. Mesh._CAP_END = 2;
  30263. Mesh._CAP_ALL = 3;
  30264. return Mesh;
  30265. }(BABYLON.AbstractMesh));
  30266. BABYLON.Mesh = Mesh;
  30267. })(BABYLON || (BABYLON = {}));
  30268. //# sourceMappingURL=babylon.mesh.js.map
  30269. var BABYLON;
  30270. (function (BABYLON) {
  30271. var BaseSubMesh = /** @class */ (function () {
  30272. function BaseSubMesh() {
  30273. }
  30274. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30275. get: function () {
  30276. return this._materialEffect;
  30277. },
  30278. enumerable: true,
  30279. configurable: true
  30280. });
  30281. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30282. if (defines === void 0) { defines = null; }
  30283. if (this._materialEffect === effect) {
  30284. if (!effect) {
  30285. this._materialDefines = null;
  30286. }
  30287. return;
  30288. }
  30289. this._materialDefines = defines;
  30290. this._materialEffect = effect;
  30291. };
  30292. return BaseSubMesh;
  30293. }());
  30294. BABYLON.BaseSubMesh = BaseSubMesh;
  30295. var SubMesh = /** @class */ (function (_super) {
  30296. __extends(SubMesh, _super);
  30297. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30298. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30299. var _this = _super.call(this) || this;
  30300. _this.materialIndex = materialIndex;
  30301. _this.verticesStart = verticesStart;
  30302. _this.verticesCount = verticesCount;
  30303. _this.indexStart = indexStart;
  30304. _this.indexCount = indexCount;
  30305. _this._renderId = 0;
  30306. _this._mesh = mesh;
  30307. _this._renderingMesh = renderingMesh || mesh;
  30308. mesh.subMeshes.push(_this);
  30309. _this._trianglePlanes = [];
  30310. _this._id = mesh.subMeshes.length - 1;
  30311. if (createBoundingBox) {
  30312. _this.refreshBoundingInfo();
  30313. mesh.computeWorldMatrix(true);
  30314. }
  30315. return _this;
  30316. }
  30317. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30318. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30319. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30320. };
  30321. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30322. get: function () {
  30323. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30324. },
  30325. enumerable: true,
  30326. configurable: true
  30327. });
  30328. /**
  30329. * Returns the submesh BoudingInfo object.
  30330. */
  30331. SubMesh.prototype.getBoundingInfo = function () {
  30332. if (this.IsGlobal) {
  30333. return this._mesh.getBoundingInfo();
  30334. }
  30335. return this._boundingInfo;
  30336. };
  30337. /**
  30338. * Sets the submesh BoundingInfo.
  30339. * Return the SubMesh.
  30340. */
  30341. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30342. this._boundingInfo = boundingInfo;
  30343. return this;
  30344. };
  30345. /**
  30346. * Returns the mesh of the current submesh.
  30347. */
  30348. SubMesh.prototype.getMesh = function () {
  30349. return this._mesh;
  30350. };
  30351. /**
  30352. * Returns the rendering mesh of the submesh.
  30353. */
  30354. SubMesh.prototype.getRenderingMesh = function () {
  30355. return this._renderingMesh;
  30356. };
  30357. /**
  30358. * Returns the submesh material.
  30359. */
  30360. SubMesh.prototype.getMaterial = function () {
  30361. var rootMaterial = this._renderingMesh.material;
  30362. if (rootMaterial === null || rootMaterial === undefined) {
  30363. return this._mesh.getScene().defaultMaterial;
  30364. }
  30365. else if (rootMaterial.getSubMaterial) {
  30366. var multiMaterial = rootMaterial;
  30367. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30368. if (this._currentMaterial !== effectiveMaterial) {
  30369. this._currentMaterial = effectiveMaterial;
  30370. this._materialDefines = null;
  30371. }
  30372. return effectiveMaterial;
  30373. }
  30374. return rootMaterial;
  30375. };
  30376. // Methods
  30377. /**
  30378. * Sets a new updated BoundingInfo object to the submesh.
  30379. * Returns the SubMesh.
  30380. */
  30381. SubMesh.prototype.refreshBoundingInfo = function () {
  30382. this._lastColliderWorldVertices = null;
  30383. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30384. return this;
  30385. }
  30386. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30387. if (!data) {
  30388. this._boundingInfo = this._mesh.getBoundingInfo();
  30389. return this;
  30390. }
  30391. var indices = this._renderingMesh.getIndices();
  30392. var extend;
  30393. //is this the only submesh?
  30394. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30395. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30396. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30397. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30398. }
  30399. else {
  30400. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30401. }
  30402. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30403. return this;
  30404. };
  30405. SubMesh.prototype._checkCollision = function (collider) {
  30406. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30407. return boundingInfo._checkCollision(collider);
  30408. };
  30409. /**
  30410. * Updates the submesh BoundingInfo.
  30411. * Returns the Submesh.
  30412. */
  30413. SubMesh.prototype.updateBoundingInfo = function (world) {
  30414. var boundingInfo = this.getBoundingInfo();
  30415. if (!boundingInfo) {
  30416. this.refreshBoundingInfo();
  30417. boundingInfo = this.getBoundingInfo();
  30418. }
  30419. boundingInfo.update(world);
  30420. return this;
  30421. };
  30422. /**
  30423. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30424. * Boolean returned.
  30425. */
  30426. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30427. var boundingInfo = this.getBoundingInfo();
  30428. if (!boundingInfo) {
  30429. return false;
  30430. }
  30431. return boundingInfo.isInFrustum(frustumPlanes);
  30432. };
  30433. /**
  30434. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30435. * Boolean returned.
  30436. */
  30437. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30438. var boundingInfo = this.getBoundingInfo();
  30439. if (!boundingInfo) {
  30440. return false;
  30441. }
  30442. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30443. };
  30444. /**
  30445. * Renders the submesh.
  30446. * Returns it.
  30447. */
  30448. SubMesh.prototype.render = function (enableAlphaMode) {
  30449. this._renderingMesh.render(this, enableAlphaMode);
  30450. return this;
  30451. };
  30452. /**
  30453. * Returns a new Index Buffer.
  30454. * Type returned : WebGLBuffer.
  30455. */
  30456. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30457. if (!this._linesIndexBuffer) {
  30458. var linesIndices = [];
  30459. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30460. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  30461. }
  30462. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  30463. this.linesIndexCount = linesIndices.length;
  30464. }
  30465. return this._linesIndexBuffer;
  30466. };
  30467. /**
  30468. * True is the passed Ray intersects the submesh bounding box.
  30469. * Boolean returned.
  30470. */
  30471. SubMesh.prototype.canIntersects = function (ray) {
  30472. var boundingInfo = this.getBoundingInfo();
  30473. if (!boundingInfo) {
  30474. return false;
  30475. }
  30476. return ray.intersectsBox(boundingInfo.boundingBox);
  30477. };
  30478. /**
  30479. * Returns an object IntersectionInfo.
  30480. */
  30481. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  30482. var intersectInfo = null;
  30483. // LineMesh first as it's also a Mesh...
  30484. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  30485. var lineMesh = this._mesh;
  30486. // Line test
  30487. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  30488. var p0 = positions[indices[index]];
  30489. var p1 = positions[indices[index + 1]];
  30490. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  30491. if (length < 0) {
  30492. continue;
  30493. }
  30494. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  30495. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  30496. if (fastCheck) {
  30497. break;
  30498. }
  30499. }
  30500. }
  30501. }
  30502. else {
  30503. // Triangles test
  30504. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30505. var p0 = positions[indices[index]];
  30506. var p1 = positions[indices[index + 1]];
  30507. var p2 = positions[indices[index + 2]];
  30508. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  30509. if (currentIntersectInfo) {
  30510. if (currentIntersectInfo.distance < 0) {
  30511. continue;
  30512. }
  30513. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  30514. intersectInfo = currentIntersectInfo;
  30515. intersectInfo.faceId = index / 3;
  30516. if (fastCheck) {
  30517. break;
  30518. }
  30519. }
  30520. }
  30521. }
  30522. }
  30523. return intersectInfo;
  30524. };
  30525. SubMesh.prototype._rebuild = function () {
  30526. if (this._linesIndexBuffer) {
  30527. this._linesIndexBuffer = null;
  30528. }
  30529. };
  30530. // Clone
  30531. /**
  30532. * Creates a new Submesh from the passed Mesh.
  30533. */
  30534. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  30535. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  30536. if (!this.IsGlobal) {
  30537. var boundingInfo = this.getBoundingInfo();
  30538. if (!boundingInfo) {
  30539. return result;
  30540. }
  30541. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  30542. }
  30543. return result;
  30544. };
  30545. // Dispose
  30546. /**
  30547. * Disposes the Submesh.
  30548. * Returns nothing.
  30549. */
  30550. SubMesh.prototype.dispose = function () {
  30551. if (this._linesIndexBuffer) {
  30552. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  30553. this._linesIndexBuffer = null;
  30554. }
  30555. // Remove from mesh
  30556. var index = this._mesh.subMeshes.indexOf(this);
  30557. this._mesh.subMeshes.splice(index, 1);
  30558. };
  30559. // Statics
  30560. /**
  30561. * Creates a new Submesh from the passed parameters :
  30562. * - materialIndex (integer) : the index of the main mesh material.
  30563. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  30564. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  30565. * - mesh (Mesh) : the main mesh to create the submesh from.
  30566. * - renderingMesh (optional Mesh) : rendering mesh.
  30567. */
  30568. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  30569. var minVertexIndex = Number.MAX_VALUE;
  30570. var maxVertexIndex = -Number.MAX_VALUE;
  30571. renderingMesh = (renderingMesh || mesh);
  30572. var indices = renderingMesh.getIndices();
  30573. for (var index = startIndex; index < startIndex + indexCount; index++) {
  30574. var vertexIndex = indices[index];
  30575. if (vertexIndex < minVertexIndex)
  30576. minVertexIndex = vertexIndex;
  30577. if (vertexIndex > maxVertexIndex)
  30578. maxVertexIndex = vertexIndex;
  30579. }
  30580. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  30581. };
  30582. return SubMesh;
  30583. }(BaseSubMesh));
  30584. BABYLON.SubMesh = SubMesh;
  30585. })(BABYLON || (BABYLON = {}));
  30586. //# sourceMappingURL=babylon.subMesh.js.map
  30587. var __assign = (this && this.__assign) || Object.assign || function(t) {
  30588. for (var s, i = 1, n = arguments.length; i < n; i++) {
  30589. s = arguments[i];
  30590. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  30591. t[p] = s[p];
  30592. }
  30593. return t;
  30594. };
  30595. var BABYLON;
  30596. (function (BABYLON) {
  30597. /**
  30598. * Manages the defines for the Material.
  30599. */
  30600. var MaterialDefines = /** @class */ (function () {
  30601. function MaterialDefines() {
  30602. this._isDirty = true;
  30603. this._areLightsDirty = true;
  30604. this._areAttributesDirty = true;
  30605. this._areTexturesDirty = true;
  30606. this._areFresnelDirty = true;
  30607. this._areMiscDirty = true;
  30608. this._areImageProcessingDirty = true;
  30609. this._normals = false;
  30610. this._uvs = false;
  30611. this._needNormals = false;
  30612. this._needUVs = false;
  30613. }
  30614. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  30615. /**
  30616. * Specifies if the material needs to be re-calculated.
  30617. */
  30618. get: function () {
  30619. return this._isDirty;
  30620. },
  30621. enumerable: true,
  30622. configurable: true
  30623. });
  30624. /**
  30625. * Marks the material to indicate that it has been re-calculated.
  30626. */
  30627. MaterialDefines.prototype.markAsProcessed = function () {
  30628. this._isDirty = false;
  30629. this._areAttributesDirty = false;
  30630. this._areTexturesDirty = false;
  30631. this._areFresnelDirty = false;
  30632. this._areLightsDirty = false;
  30633. this._areMiscDirty = false;
  30634. this._areImageProcessingDirty = false;
  30635. };
  30636. /**
  30637. * Marks the material to indicate that it needs to be re-calculated.
  30638. */
  30639. MaterialDefines.prototype.markAsUnprocessed = function () {
  30640. this._isDirty = true;
  30641. };
  30642. /**
  30643. * Marks the material to indicate all of its defines need to be re-calculated.
  30644. */
  30645. MaterialDefines.prototype.markAllAsDirty = function () {
  30646. this._areTexturesDirty = true;
  30647. this._areAttributesDirty = true;
  30648. this._areLightsDirty = true;
  30649. this._areFresnelDirty = true;
  30650. this._areMiscDirty = true;
  30651. this._areImageProcessingDirty = true;
  30652. this._isDirty = true;
  30653. };
  30654. /**
  30655. * Marks the material to indicate that image processing needs to be re-calculated.
  30656. */
  30657. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  30658. this._areImageProcessingDirty = true;
  30659. this._isDirty = true;
  30660. };
  30661. /**
  30662. * Marks the material to indicate the lights need to be re-calculated.
  30663. */
  30664. MaterialDefines.prototype.markAsLightDirty = function () {
  30665. this._areLightsDirty = true;
  30666. this._isDirty = true;
  30667. };
  30668. /**
  30669. * Marks the attribute state as changed.
  30670. */
  30671. MaterialDefines.prototype.markAsAttributesDirty = function () {
  30672. this._areAttributesDirty = true;
  30673. this._isDirty = true;
  30674. };
  30675. /**
  30676. * Marks the texture state as changed.
  30677. */
  30678. MaterialDefines.prototype.markAsTexturesDirty = function () {
  30679. this._areTexturesDirty = true;
  30680. this._isDirty = true;
  30681. };
  30682. /**
  30683. * Marks the fresnel state as changed.
  30684. */
  30685. MaterialDefines.prototype.markAsFresnelDirty = function () {
  30686. this._areFresnelDirty = true;
  30687. this._isDirty = true;
  30688. };
  30689. /**
  30690. * Marks the misc state as changed.
  30691. */
  30692. MaterialDefines.prototype.markAsMiscDirty = function () {
  30693. this._areMiscDirty = true;
  30694. this._isDirty = true;
  30695. };
  30696. /**
  30697. * Rebuilds the material defines.
  30698. */
  30699. MaterialDefines.prototype.rebuild = function () {
  30700. if (this._keys) {
  30701. delete this._keys;
  30702. }
  30703. this._keys = [];
  30704. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  30705. var key = _a[_i];
  30706. if (key[0] === "_") {
  30707. continue;
  30708. }
  30709. this._keys.push(key);
  30710. }
  30711. };
  30712. /**
  30713. * Specifies if two material defines are equal.
  30714. * @param other - A material define instance to compare to.
  30715. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  30716. */
  30717. MaterialDefines.prototype.isEqual = function (other) {
  30718. if (this._keys.length !== other._keys.length) {
  30719. return false;
  30720. }
  30721. for (var index = 0; index < this._keys.length; index++) {
  30722. var prop = this._keys[index];
  30723. if (this[prop] !== other[prop]) {
  30724. return false;
  30725. }
  30726. }
  30727. return true;
  30728. };
  30729. /**
  30730. * Clones this instance's defines to another instance.
  30731. * @param other - material defines to clone values to.
  30732. */
  30733. MaterialDefines.prototype.cloneTo = function (other) {
  30734. if (this._keys.length !== other._keys.length) {
  30735. other._keys = this._keys.slice(0);
  30736. }
  30737. for (var index = 0; index < this._keys.length; index++) {
  30738. var prop = this._keys[index];
  30739. other[prop] = this[prop];
  30740. }
  30741. };
  30742. /**
  30743. * Resets the material define values.
  30744. */
  30745. MaterialDefines.prototype.reset = function () {
  30746. for (var index = 0; index < this._keys.length; index++) {
  30747. var prop = this._keys[index];
  30748. if (typeof (this[prop]) === "number") {
  30749. this[prop] = 0;
  30750. }
  30751. else {
  30752. this[prop] = false;
  30753. }
  30754. }
  30755. };
  30756. /**
  30757. * Converts the material define values to a string.
  30758. * @returns - String of material define information.
  30759. */
  30760. MaterialDefines.prototype.toString = function () {
  30761. var result = "";
  30762. for (var index = 0; index < this._keys.length; index++) {
  30763. var prop = this._keys[index];
  30764. var value = this[prop];
  30765. if (typeof (value) === "number") {
  30766. result += "#define " + prop + " " + this[prop] + "\n";
  30767. }
  30768. else if (value) {
  30769. result += "#define " + prop + "\n";
  30770. }
  30771. }
  30772. return result;
  30773. };
  30774. return MaterialDefines;
  30775. }());
  30776. BABYLON.MaterialDefines = MaterialDefines;
  30777. /**
  30778. * This offers the main features of a material in BJS.
  30779. */
  30780. var Material = /** @class */ (function () {
  30781. /**
  30782. * Creates a material instance.
  30783. * @param name - The name of the material.
  30784. * @param scene - The BJS scene to reference.
  30785. * @param doNotAdd - Specifies if the material should be added to the scene.
  30786. */
  30787. function Material(name, scene, doNotAdd) {
  30788. /**
  30789. * Specifies if the ready state should be checked on each call.
  30790. */
  30791. this.checkReadyOnEveryCall = false;
  30792. /**
  30793. * Specifies if the ready state should be checked once.
  30794. */
  30795. this.checkReadyOnlyOnce = false;
  30796. /**
  30797. * The state of the material.
  30798. */
  30799. this.state = "";
  30800. /**
  30801. * The alpha value of the material.
  30802. */
  30803. this._alpha = 1.0;
  30804. /**
  30805. * Specifies if back face culling is enabled.
  30806. */
  30807. this._backFaceCulling = true;
  30808. /**
  30809. * Specifies if the material should be serialized.
  30810. */
  30811. this.doNotSerialize = false;
  30812. /**
  30813. * Specifies if the effect should be stored on sub meshes.
  30814. */
  30815. this.storeEffectOnSubMeshes = false;
  30816. /**
  30817. * An event triggered when the material is disposed.
  30818. * @type {BABYLON.Observable}
  30819. */
  30820. this.onDisposeObservable = new BABYLON.Observable();
  30821. /**
  30822. * An event triggered when the material is bound.
  30823. * @type {BABYLON.Observable}
  30824. */
  30825. this.onBindObservable = new BABYLON.Observable();
  30826. /**
  30827. * An event triggered when the material is unbound.
  30828. * @type {BABYLON.Observable}
  30829. */
  30830. this.onUnBindObservable = new BABYLON.Observable();
  30831. /**
  30832. * Stores the value of the alpha mode.
  30833. */
  30834. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  30835. /**
  30836. * Stores the state of the need depth pre-pass value.
  30837. */
  30838. this._needDepthPrePass = false;
  30839. /**
  30840. * Specifies if depth writing should be disabled.
  30841. */
  30842. this.disableDepthWrite = false;
  30843. /**
  30844. * Specifies if depth writing should be forced.
  30845. */
  30846. this.forceDepthWrite = false;
  30847. /**
  30848. * Specifies if there should be a separate pass for culling.
  30849. */
  30850. this.separateCullingPass = false;
  30851. /**
  30852. * Stores the state specifing if fog should be enabled.
  30853. */
  30854. this._fogEnabled = true;
  30855. /**
  30856. * Stores the size of points.
  30857. */
  30858. this.pointSize = 1.0;
  30859. /**
  30860. * Stores the z offset value.
  30861. */
  30862. this.zOffset = 0;
  30863. /**
  30864. * Specifies if the material was previously ready.
  30865. */
  30866. this._wasPreviouslyReady = false;
  30867. /**
  30868. * Stores the fill mode state.
  30869. */
  30870. this._fillMode = Material.TriangleFillMode;
  30871. this.name = name;
  30872. this.id = name || BABYLON.Tools.RandomId();
  30873. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30874. if (this._scene.useRightHandedSystem) {
  30875. this.sideOrientation = Material.ClockWiseSideOrientation;
  30876. }
  30877. else {
  30878. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  30879. }
  30880. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  30881. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  30882. if (!doNotAdd) {
  30883. this._scene.materials.push(this);
  30884. }
  30885. }
  30886. Object.defineProperty(Material, "TriangleFillMode", {
  30887. /**
  30888. * Returns the triangle fill mode.
  30889. */
  30890. get: function () {
  30891. return Material._TriangleFillMode;
  30892. },
  30893. enumerable: true,
  30894. configurable: true
  30895. });
  30896. Object.defineProperty(Material, "WireFrameFillMode", {
  30897. /**
  30898. * Returns the wireframe mode.
  30899. */
  30900. get: function () {
  30901. return Material._WireFrameFillMode;
  30902. },
  30903. enumerable: true,
  30904. configurable: true
  30905. });
  30906. Object.defineProperty(Material, "PointFillMode", {
  30907. /**
  30908. * Returns the point fill mode.
  30909. */
  30910. get: function () {
  30911. return Material._PointFillMode;
  30912. },
  30913. enumerable: true,
  30914. configurable: true
  30915. });
  30916. Object.defineProperty(Material, "PointListDrawMode", {
  30917. /**
  30918. * Returns the point list draw mode.
  30919. */
  30920. get: function () {
  30921. return Material._PointListDrawMode;
  30922. },
  30923. enumerable: true,
  30924. configurable: true
  30925. });
  30926. Object.defineProperty(Material, "LineListDrawMode", {
  30927. /**
  30928. * Returns the line list draw mode.
  30929. */
  30930. get: function () {
  30931. return Material._LineListDrawMode;
  30932. },
  30933. enumerable: true,
  30934. configurable: true
  30935. });
  30936. Object.defineProperty(Material, "LineLoopDrawMode", {
  30937. /**
  30938. * Returns the line loop draw mode.
  30939. */
  30940. get: function () {
  30941. return Material._LineLoopDrawMode;
  30942. },
  30943. enumerable: true,
  30944. configurable: true
  30945. });
  30946. Object.defineProperty(Material, "LineStripDrawMode", {
  30947. /**
  30948. * Returns the line strip draw mode.
  30949. */
  30950. get: function () {
  30951. return Material._LineStripDrawMode;
  30952. },
  30953. enumerable: true,
  30954. configurable: true
  30955. });
  30956. Object.defineProperty(Material, "TriangleStripDrawMode", {
  30957. /**
  30958. * Returns the triangle strip draw mode.
  30959. */
  30960. get: function () {
  30961. return Material._TriangleStripDrawMode;
  30962. },
  30963. enumerable: true,
  30964. configurable: true
  30965. });
  30966. Object.defineProperty(Material, "TriangleFanDrawMode", {
  30967. /**
  30968. * Returns the triangle fan draw mode.
  30969. */
  30970. get: function () {
  30971. return Material._TriangleFanDrawMode;
  30972. },
  30973. enumerable: true,
  30974. configurable: true
  30975. });
  30976. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  30977. /**
  30978. * Returns the clock-wise side orientation.
  30979. */
  30980. get: function () {
  30981. return Material._ClockWiseSideOrientation;
  30982. },
  30983. enumerable: true,
  30984. configurable: true
  30985. });
  30986. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  30987. /**
  30988. * Returns the counter clock-wise side orientation.
  30989. */
  30990. get: function () {
  30991. return Material._CounterClockWiseSideOrientation;
  30992. },
  30993. enumerable: true,
  30994. configurable: true
  30995. });
  30996. Object.defineProperty(Material, "TextureDirtyFlag", {
  30997. /**
  30998. * Returns the dirty texture flag value.
  30999. */
  31000. get: function () {
  31001. return Material._TextureDirtyFlag;
  31002. },
  31003. enumerable: true,
  31004. configurable: true
  31005. });
  31006. Object.defineProperty(Material, "LightDirtyFlag", {
  31007. /**
  31008. * Returns the dirty light flag value.
  31009. */
  31010. get: function () {
  31011. return Material._LightDirtyFlag;
  31012. },
  31013. enumerable: true,
  31014. configurable: true
  31015. });
  31016. Object.defineProperty(Material, "FresnelDirtyFlag", {
  31017. /**
  31018. * Returns the dirty fresnel flag value.
  31019. */
  31020. get: function () {
  31021. return Material._FresnelDirtyFlag;
  31022. },
  31023. enumerable: true,
  31024. configurable: true
  31025. });
  31026. Object.defineProperty(Material, "AttributesDirtyFlag", {
  31027. /**
  31028. * Returns the dirty attributes flag value.
  31029. */
  31030. get: function () {
  31031. return Material._AttributesDirtyFlag;
  31032. },
  31033. enumerable: true,
  31034. configurable: true
  31035. });
  31036. Object.defineProperty(Material, "MiscDirtyFlag", {
  31037. /**
  31038. * Returns the dirty misc flag value.
  31039. */
  31040. get: function () {
  31041. return Material._MiscDirtyFlag;
  31042. },
  31043. enumerable: true,
  31044. configurable: true
  31045. });
  31046. Object.defineProperty(Material.prototype, "alpha", {
  31047. /**
  31048. * Gets the alpha value of the material.
  31049. */
  31050. get: function () {
  31051. return this._alpha;
  31052. },
  31053. /**
  31054. * Sets the alpha value of the material.
  31055. */
  31056. set: function (value) {
  31057. if (this._alpha === value) {
  31058. return;
  31059. }
  31060. this._alpha = value;
  31061. this.markAsDirty(Material.MiscDirtyFlag);
  31062. },
  31063. enumerable: true,
  31064. configurable: true
  31065. });
  31066. Object.defineProperty(Material.prototype, "backFaceCulling", {
  31067. /**
  31068. * Gets the back-face culling state.
  31069. */
  31070. get: function () {
  31071. return this._backFaceCulling;
  31072. },
  31073. /**
  31074. * Sets the back-face culling state.
  31075. */
  31076. set: function (value) {
  31077. if (this._backFaceCulling === value) {
  31078. return;
  31079. }
  31080. this._backFaceCulling = value;
  31081. this.markAsDirty(Material.TextureDirtyFlag);
  31082. },
  31083. enumerable: true,
  31084. configurable: true
  31085. });
  31086. Object.defineProperty(Material.prototype, "onDispose", {
  31087. /**
  31088. * Called during a dispose event.
  31089. */
  31090. set: function (callback) {
  31091. if (this._onDisposeObserver) {
  31092. this.onDisposeObservable.remove(this._onDisposeObserver);
  31093. }
  31094. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31095. },
  31096. enumerable: true,
  31097. configurable: true
  31098. });
  31099. Object.defineProperty(Material.prototype, "onBind", {
  31100. /**
  31101. * Called during a bind event.
  31102. */
  31103. set: function (callback) {
  31104. if (this._onBindObserver) {
  31105. this.onBindObservable.remove(this._onBindObserver);
  31106. }
  31107. this._onBindObserver = this.onBindObservable.add(callback);
  31108. },
  31109. enumerable: true,
  31110. configurable: true
  31111. });
  31112. Object.defineProperty(Material.prototype, "alphaMode", {
  31113. /**
  31114. * Gets the value of the alpha mode.
  31115. */
  31116. get: function () {
  31117. return this._alphaMode;
  31118. },
  31119. /**
  31120. * Sets the value of the alpha mode.
  31121. */
  31122. set: function (value) {
  31123. if (this._alphaMode === value) {
  31124. return;
  31125. }
  31126. this._alphaMode = value;
  31127. this.markAsDirty(Material.TextureDirtyFlag);
  31128. },
  31129. enumerable: true,
  31130. configurable: true
  31131. });
  31132. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31133. /**
  31134. * Gets the depth pre-pass value.
  31135. */
  31136. get: function () {
  31137. return this._needDepthPrePass;
  31138. },
  31139. /**
  31140. * Sets the need depth pre-pass value.
  31141. */
  31142. set: function (value) {
  31143. if (this._needDepthPrePass === value) {
  31144. return;
  31145. }
  31146. this._needDepthPrePass = value;
  31147. if (this._needDepthPrePass) {
  31148. this.checkReadyOnEveryCall = true;
  31149. }
  31150. },
  31151. enumerable: true,
  31152. configurable: true
  31153. });
  31154. Object.defineProperty(Material.prototype, "fogEnabled", {
  31155. /**
  31156. * Gets the value of the fog enabled state.
  31157. */
  31158. get: function () {
  31159. return this._fogEnabled;
  31160. },
  31161. /**
  31162. * Sets the state for enabling fog.
  31163. */
  31164. set: function (value) {
  31165. if (this._fogEnabled === value) {
  31166. return;
  31167. }
  31168. this._fogEnabled = value;
  31169. this.markAsDirty(Material.MiscDirtyFlag);
  31170. },
  31171. enumerable: true,
  31172. configurable: true
  31173. });
  31174. Object.defineProperty(Material.prototype, "wireframe", {
  31175. /**
  31176. * Gets a value specifying if wireframe mode is enabled.
  31177. */
  31178. get: function () {
  31179. return this._fillMode === Material.WireFrameFillMode;
  31180. },
  31181. /**
  31182. * Sets the state of wireframe mode.
  31183. */
  31184. set: function (value) {
  31185. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31186. },
  31187. enumerable: true,
  31188. configurable: true
  31189. });
  31190. Object.defineProperty(Material.prototype, "pointsCloud", {
  31191. /**
  31192. * Gets the value specifying if point clouds are enabled.
  31193. */
  31194. get: function () {
  31195. return this._fillMode === Material.PointFillMode;
  31196. },
  31197. /**
  31198. * Sets the state of point cloud mode.
  31199. */
  31200. set: function (value) {
  31201. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31202. },
  31203. enumerable: true,
  31204. configurable: true
  31205. });
  31206. Object.defineProperty(Material.prototype, "fillMode", {
  31207. /**
  31208. * Gets the material fill mode.
  31209. */
  31210. get: function () {
  31211. return this._fillMode;
  31212. },
  31213. /**
  31214. * Sets the material fill mode.
  31215. */
  31216. set: function (value) {
  31217. if (this._fillMode === value) {
  31218. return;
  31219. }
  31220. this._fillMode = value;
  31221. this.markAsDirty(Material.MiscDirtyFlag);
  31222. },
  31223. enumerable: true,
  31224. configurable: true
  31225. });
  31226. /**
  31227. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31228. * subclasses should override adding information pertainent to themselves.
  31229. * @returns - String with material information.
  31230. */
  31231. Material.prototype.toString = function (fullDetails) {
  31232. var ret = "Name: " + this.name;
  31233. if (fullDetails) {
  31234. }
  31235. return ret;
  31236. };
  31237. /**
  31238. * Gets the class name of the material.
  31239. * @returns - String with the class name of the material.
  31240. */
  31241. Material.prototype.getClassName = function () {
  31242. return "Material";
  31243. };
  31244. Object.defineProperty(Material.prototype, "isFrozen", {
  31245. /**
  31246. * Specifies if updates for the material been locked.
  31247. */
  31248. get: function () {
  31249. return this.checkReadyOnlyOnce;
  31250. },
  31251. enumerable: true,
  31252. configurable: true
  31253. });
  31254. /**
  31255. * Locks updates for the material.
  31256. */
  31257. Material.prototype.freeze = function () {
  31258. this.checkReadyOnlyOnce = true;
  31259. };
  31260. /**
  31261. * Unlocks updates for the material.
  31262. */
  31263. Material.prototype.unfreeze = function () {
  31264. this.checkReadyOnlyOnce = false;
  31265. };
  31266. /**
  31267. * Specifies if the material is ready to be used.
  31268. * @param mesh - BJS mesh.
  31269. * @param useInstances - Specifies if instances should be used.
  31270. * @returns - Boolean indicating if the material is ready to be used.
  31271. */
  31272. Material.prototype.isReady = function (mesh, useInstances) {
  31273. return true;
  31274. };
  31275. /**
  31276. * Specifies that the submesh is ready to be used.
  31277. * @param mesh - BJS mesh.
  31278. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31279. * @param useInstances - Specifies that instances should be used.
  31280. * @returns - boolean indicating that the submesh is ready or not.
  31281. */
  31282. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31283. return false;
  31284. };
  31285. /**
  31286. * Returns the material effect.
  31287. * @returns - Nullable material effect.
  31288. */
  31289. Material.prototype.getEffect = function () {
  31290. return this._effect;
  31291. };
  31292. /**
  31293. * Returns the BJS scene.
  31294. * @returns - BJS Scene.
  31295. */
  31296. Material.prototype.getScene = function () {
  31297. return this._scene;
  31298. };
  31299. /**
  31300. * Specifies if the material will require alpha blending
  31301. * @returns - Boolean specifying if alpha blending is needed.
  31302. */
  31303. Material.prototype.needAlphaBlending = function () {
  31304. return (this.alpha < 1.0);
  31305. };
  31306. /**
  31307. * Specifies if the mesh will require alpha blending.
  31308. * @param mesh - BJS mesh.
  31309. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31310. */
  31311. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  31312. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  31313. };
  31314. /**
  31315. * Specifies if this material should be rendered in alpha test mode.
  31316. * @returns - Boolean specifying if an alpha test is needed.
  31317. */
  31318. Material.prototype.needAlphaTesting = function () {
  31319. return false;
  31320. };
  31321. /**
  31322. * Gets the texture used for the alpha test.
  31323. * @returns - Nullable alpha test texture.
  31324. */
  31325. Material.prototype.getAlphaTestTexture = function () {
  31326. return null;
  31327. };
  31328. /**
  31329. * Marks the material to indicate that it needs to be re-calculated.
  31330. */
  31331. Material.prototype.markDirty = function () {
  31332. this._wasPreviouslyReady = false;
  31333. };
  31334. Material.prototype._preBind = function (effect, overrideOrientation) {
  31335. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31336. var engine = this._scene.getEngine();
  31337. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31338. var reverse = orientation === Material.ClockWiseSideOrientation;
  31339. engine.enableEffect(effect ? effect : this._effect);
  31340. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31341. return reverse;
  31342. };
  31343. /**
  31344. * Binds the material to the mesh.
  31345. * @param world - World transformation matrix.
  31346. * @param mesh - Mesh to bind the material to.
  31347. */
  31348. Material.prototype.bind = function (world, mesh) {
  31349. };
  31350. /**
  31351. * Binds the submesh to the material.
  31352. * @param world - World transformation matrix.
  31353. * @param mesh - Mesh containing the submesh.
  31354. * @param subMesh - Submesh to bind the material to.
  31355. */
  31356. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31357. };
  31358. /**
  31359. * Binds the world matrix to the material.
  31360. * @param world - World transformation matrix.
  31361. */
  31362. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31363. };
  31364. /**
  31365. * Binds the scene's uniform buffer to the effect.
  31366. * @param effect - Effect to bind to the scene uniform buffer.
  31367. * @param sceneUbo - Scene uniform buffer.
  31368. */
  31369. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  31370. sceneUbo.bindToEffect(effect, "Scene");
  31371. };
  31372. /**
  31373. * Binds the view matrix to the effect.
  31374. * @param effect - Effect to bind the view matrix to.
  31375. */
  31376. Material.prototype.bindView = function (effect) {
  31377. if (!this._useUBO) {
  31378. effect.setMatrix("view", this.getScene().getViewMatrix());
  31379. }
  31380. else {
  31381. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31382. }
  31383. };
  31384. /**
  31385. * Binds the view projection matrix to the effect.
  31386. * @param effect - Effect to bind the view projection matrix to.
  31387. */
  31388. Material.prototype.bindViewProjection = function (effect) {
  31389. if (!this._useUBO) {
  31390. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  31391. }
  31392. else {
  31393. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31394. }
  31395. };
  31396. /**
  31397. * Specifies if material alpha testing should be turned on for the mesh.
  31398. * @param mesh - BJS mesh.
  31399. */
  31400. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  31401. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  31402. };
  31403. /**
  31404. * Processes to execute after binding the material to a mesh.
  31405. * @param mesh - BJS mesh.
  31406. */
  31407. Material.prototype._afterBind = function (mesh) {
  31408. this._scene._cachedMaterial = this;
  31409. if (mesh) {
  31410. this._scene._cachedVisibility = mesh.visibility;
  31411. }
  31412. else {
  31413. this._scene._cachedVisibility = 1;
  31414. }
  31415. if (mesh) {
  31416. this.onBindObservable.notifyObservers(mesh);
  31417. }
  31418. if (this.disableDepthWrite) {
  31419. var engine = this._scene.getEngine();
  31420. this._cachedDepthWriteState = engine.getDepthWrite();
  31421. engine.setDepthWrite(false);
  31422. }
  31423. };
  31424. /**
  31425. * Unbinds the material from the mesh.
  31426. */
  31427. Material.prototype.unbind = function () {
  31428. this.onUnBindObservable.notifyObservers(this);
  31429. if (this.disableDepthWrite) {
  31430. var engine = this._scene.getEngine();
  31431. engine.setDepthWrite(this._cachedDepthWriteState);
  31432. }
  31433. };
  31434. /**
  31435. * Gets the active textures from the material.
  31436. * @returns - Array of textures.
  31437. */
  31438. Material.prototype.getActiveTextures = function () {
  31439. return [];
  31440. };
  31441. /**
  31442. * Specifies if the material uses a texture.
  31443. * @param texture - Texture to check against the material.
  31444. * @returns - Boolean specifying if the material uses the texture.
  31445. */
  31446. Material.prototype.hasTexture = function (texture) {
  31447. return false;
  31448. };
  31449. /**
  31450. * Makes a duplicate of the material, and gives it a new name.
  31451. * @param name - Name to call the duplicated material.
  31452. * @returns - Nullable cloned material
  31453. */
  31454. Material.prototype.clone = function (name) {
  31455. return null;
  31456. };
  31457. /**
  31458. * Gets the meshes bound to the material.
  31459. * @returns - Array of meshes bound to the material.
  31460. */
  31461. Material.prototype.getBindedMeshes = function () {
  31462. var result = new Array();
  31463. for (var index = 0; index < this._scene.meshes.length; index++) {
  31464. var mesh = this._scene.meshes[index];
  31465. if (mesh.material === this) {
  31466. result.push(mesh);
  31467. }
  31468. }
  31469. return result;
  31470. };
  31471. /**
  31472. * Force shader compilation
  31473. * @param mesh - BJS mesh.
  31474. * @param onCompiled - function to execute once the material is compiled.
  31475. * @param options - options to pass to this function.
  31476. */
  31477. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  31478. var _this = this;
  31479. var localOptions = __assign({ clipPlane: false }, options);
  31480. var subMesh = new BABYLON.BaseSubMesh();
  31481. var scene = this.getScene();
  31482. var checkReady = function () {
  31483. if (!_this._scene || !_this._scene.getEngine()) {
  31484. return;
  31485. }
  31486. if (subMesh._materialDefines) {
  31487. subMesh._materialDefines._renderId = -1;
  31488. }
  31489. var clipPlaneState = scene.clipPlane;
  31490. if (localOptions.clipPlane) {
  31491. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  31492. }
  31493. if (_this.storeEffectOnSubMeshes) {
  31494. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  31495. if (onCompiled) {
  31496. onCompiled(_this);
  31497. }
  31498. }
  31499. else {
  31500. setTimeout(checkReady, 16);
  31501. }
  31502. }
  31503. else {
  31504. if (_this.isReady(mesh)) {
  31505. if (onCompiled) {
  31506. onCompiled(_this);
  31507. }
  31508. }
  31509. else {
  31510. setTimeout(checkReady, 16);
  31511. }
  31512. }
  31513. if (localOptions.clipPlane) {
  31514. scene.clipPlane = clipPlaneState;
  31515. }
  31516. };
  31517. checkReady();
  31518. };
  31519. /**
  31520. * Force shader compilation.
  31521. * @param mesh The mesh that will use this material
  31522. * @param options Additional options for compiling the shaders
  31523. * @returns A promise that resolves when the compilation completes
  31524. */
  31525. Material.prototype.forceCompilationAsync = function (mesh, options) {
  31526. var _this = this;
  31527. return new Promise(function (resolve) {
  31528. _this.forceCompilation(mesh, function () {
  31529. resolve();
  31530. }, options);
  31531. });
  31532. };
  31533. /**
  31534. * Marks a define in the material to indicate that it needs to be re-computed.
  31535. * @param flag - Material define flag.
  31536. */
  31537. Material.prototype.markAsDirty = function (flag) {
  31538. if (flag & Material.TextureDirtyFlag) {
  31539. this._markAllSubMeshesAsTexturesDirty();
  31540. }
  31541. if (flag & Material.LightDirtyFlag) {
  31542. this._markAllSubMeshesAsLightsDirty();
  31543. }
  31544. if (flag & Material.FresnelDirtyFlag) {
  31545. this._markAllSubMeshesAsFresnelDirty();
  31546. }
  31547. if (flag & Material.AttributesDirtyFlag) {
  31548. this._markAllSubMeshesAsAttributesDirty();
  31549. }
  31550. if (flag & Material.MiscDirtyFlag) {
  31551. this._markAllSubMeshesAsMiscDirty();
  31552. }
  31553. this.getScene().resetCachedMaterial();
  31554. };
  31555. /**
  31556. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  31557. * @param func - function which checks material defines against the submeshes.
  31558. */
  31559. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  31560. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  31561. var mesh = _a[_i];
  31562. if (!mesh.subMeshes) {
  31563. continue;
  31564. }
  31565. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  31566. var subMesh = _c[_b];
  31567. if (subMesh.getMaterial() !== this) {
  31568. continue;
  31569. }
  31570. if (!subMesh._materialDefines) {
  31571. continue;
  31572. }
  31573. func(subMesh._materialDefines);
  31574. }
  31575. }
  31576. };
  31577. /**
  31578. * Indicates that image processing needs to be re-calculated for all submeshes.
  31579. */
  31580. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  31581. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  31582. };
  31583. /**
  31584. * Indicates that textures need to be re-calculated for all submeshes.
  31585. */
  31586. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  31587. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  31588. };
  31589. /**
  31590. * Indicates that fresnel needs to be re-calculated for all submeshes.
  31591. */
  31592. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  31593. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  31594. };
  31595. /**
  31596. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  31597. */
  31598. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  31599. this._markAllSubMeshesAsDirty(function (defines) {
  31600. defines.markAsFresnelDirty();
  31601. defines.markAsMiscDirty();
  31602. });
  31603. };
  31604. /**
  31605. * Indicates that lights need to be re-calculated for all submeshes.
  31606. */
  31607. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  31608. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  31609. };
  31610. /**
  31611. * Indicates that attributes need to be re-calculated for all submeshes.
  31612. */
  31613. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  31614. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  31615. };
  31616. /**
  31617. * Indicates that misc needs to be re-calculated for all submeshes.
  31618. */
  31619. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  31620. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  31621. };
  31622. /**
  31623. * Indicates that textures and misc need to be re-calculated for all submeshes.
  31624. */
  31625. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  31626. this._markAllSubMeshesAsDirty(function (defines) {
  31627. defines.markAsTexturesDirty();
  31628. defines.markAsMiscDirty();
  31629. });
  31630. };
  31631. /**
  31632. * Disposes the material.
  31633. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  31634. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  31635. */
  31636. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31637. // Animations
  31638. this.getScene().stopAnimation(this);
  31639. // Remove from scene
  31640. var index = this._scene.materials.indexOf(this);
  31641. if (index >= 0) {
  31642. this._scene.materials.splice(index, 1);
  31643. }
  31644. // Remove from meshes
  31645. for (index = 0; index < this._scene.meshes.length; index++) {
  31646. var mesh = this._scene.meshes[index];
  31647. if (mesh.material === this) {
  31648. mesh.material = null;
  31649. if (mesh.geometry) {
  31650. var geometry = (mesh.geometry);
  31651. if (this.storeEffectOnSubMeshes) {
  31652. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  31653. var subMesh = _a[_i];
  31654. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  31655. if (forceDisposeEffect && subMesh._materialEffect) {
  31656. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  31657. }
  31658. }
  31659. }
  31660. else {
  31661. geometry._releaseVertexArrayObject(this._effect);
  31662. }
  31663. }
  31664. }
  31665. }
  31666. this._uniformBuffer.dispose();
  31667. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  31668. if (forceDisposeEffect && this._effect) {
  31669. if (!this.storeEffectOnSubMeshes) {
  31670. this._scene.getEngine()._releaseEffect(this._effect);
  31671. }
  31672. this._effect = null;
  31673. }
  31674. // Callback
  31675. this.onDisposeObservable.notifyObservers(this);
  31676. this.onDisposeObservable.clear();
  31677. this.onBindObservable.clear();
  31678. this.onUnBindObservable.clear();
  31679. };
  31680. /**
  31681. * Serializes this material.
  31682. * @returns - serialized material object.
  31683. */
  31684. Material.prototype.serialize = function () {
  31685. return BABYLON.SerializationHelper.Serialize(this);
  31686. };
  31687. /**
  31688. * Creates a MultiMaterial from parse MultiMaterial data.
  31689. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  31690. * @param scene - BJS scene.
  31691. * @returns - MultiMaterial.
  31692. */
  31693. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  31694. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  31695. multiMaterial.id = parsedMultiMaterial.id;
  31696. if (BABYLON.Tags) {
  31697. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  31698. }
  31699. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  31700. var subMatId = parsedMultiMaterial.materials[matIndex];
  31701. if (subMatId) {
  31702. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  31703. }
  31704. else {
  31705. multiMaterial.subMaterials.push(null);
  31706. }
  31707. }
  31708. return multiMaterial;
  31709. };
  31710. /**
  31711. * Creates a material from parsed material data.
  31712. * @param parsedMaterial - Parsed material data.
  31713. * @param scene - BJS scene.
  31714. * @param rootUrl - Root URL containing the material information.
  31715. * @returns - Parsed material.
  31716. */
  31717. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  31718. if (!parsedMaterial.customType) {
  31719. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  31720. }
  31721. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  31722. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  31723. if (!BABYLON.LegacyPBRMaterial) {
  31724. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  31725. return;
  31726. }
  31727. }
  31728. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  31729. return materialType.Parse(parsedMaterial, scene, rootUrl);
  31730. ;
  31731. };
  31732. // Triangle views
  31733. Material._TriangleFillMode = 0;
  31734. Material._WireFrameFillMode = 1;
  31735. Material._PointFillMode = 2;
  31736. // Draw modes
  31737. Material._PointListDrawMode = 3;
  31738. Material._LineListDrawMode = 4;
  31739. Material._LineLoopDrawMode = 5;
  31740. Material._LineStripDrawMode = 6;
  31741. Material._TriangleStripDrawMode = 7;
  31742. Material._TriangleFanDrawMode = 8;
  31743. /**
  31744. * Stores the clock-wise side orientation.
  31745. */
  31746. Material._ClockWiseSideOrientation = 0;
  31747. /**
  31748. * Stores the counter clock-wise side orientation.
  31749. */
  31750. Material._CounterClockWiseSideOrientation = 1;
  31751. /**
  31752. * The dirty texture flag value.
  31753. */
  31754. Material._TextureDirtyFlag = 1;
  31755. /**
  31756. * The dirty light flag value.
  31757. */
  31758. Material._LightDirtyFlag = 2;
  31759. /**
  31760. * The dirty fresnel flag value.
  31761. */
  31762. Material._FresnelDirtyFlag = 4;
  31763. /**
  31764. * The dirty attribute flag value.
  31765. */
  31766. Material._AttributesDirtyFlag = 8;
  31767. /**
  31768. * The dirty misc flag value.
  31769. */
  31770. Material._MiscDirtyFlag = 16;
  31771. __decorate([
  31772. BABYLON.serialize()
  31773. ], Material.prototype, "id", void 0);
  31774. __decorate([
  31775. BABYLON.serialize()
  31776. ], Material.prototype, "name", void 0);
  31777. __decorate([
  31778. BABYLON.serialize()
  31779. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  31780. __decorate([
  31781. BABYLON.serialize()
  31782. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  31783. __decorate([
  31784. BABYLON.serialize()
  31785. ], Material.prototype, "state", void 0);
  31786. __decorate([
  31787. BABYLON.serialize("alpha")
  31788. ], Material.prototype, "_alpha", void 0);
  31789. __decorate([
  31790. BABYLON.serialize("backFaceCulling")
  31791. ], Material.prototype, "_backFaceCulling", void 0);
  31792. __decorate([
  31793. BABYLON.serialize()
  31794. ], Material.prototype, "sideOrientation", void 0);
  31795. __decorate([
  31796. BABYLON.serialize("alphaMode")
  31797. ], Material.prototype, "_alphaMode", void 0);
  31798. __decorate([
  31799. BABYLON.serialize()
  31800. ], Material.prototype, "_needDepthPrePass", void 0);
  31801. __decorate([
  31802. BABYLON.serialize()
  31803. ], Material.prototype, "disableDepthWrite", void 0);
  31804. __decorate([
  31805. BABYLON.serialize()
  31806. ], Material.prototype, "forceDepthWrite", void 0);
  31807. __decorate([
  31808. BABYLON.serialize()
  31809. ], Material.prototype, "separateCullingPass", void 0);
  31810. __decorate([
  31811. BABYLON.serialize("fogEnabled")
  31812. ], Material.prototype, "_fogEnabled", void 0);
  31813. __decorate([
  31814. BABYLON.serialize()
  31815. ], Material.prototype, "pointSize", void 0);
  31816. __decorate([
  31817. BABYLON.serialize()
  31818. ], Material.prototype, "zOffset", void 0);
  31819. __decorate([
  31820. BABYLON.serialize()
  31821. ], Material.prototype, "wireframe", null);
  31822. __decorate([
  31823. BABYLON.serialize()
  31824. ], Material.prototype, "pointsCloud", null);
  31825. __decorate([
  31826. BABYLON.serialize()
  31827. ], Material.prototype, "fillMode", null);
  31828. return Material;
  31829. }());
  31830. BABYLON.Material = Material;
  31831. })(BABYLON || (BABYLON = {}));
  31832. //# sourceMappingURL=babylon.material.js.map
  31833. var BABYLON;
  31834. (function (BABYLON) {
  31835. var UniformBuffer = /** @class */ (function () {
  31836. /**
  31837. * Uniform buffer objects.
  31838. *
  31839. * Handles blocks of uniform on the GPU.
  31840. *
  31841. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  31842. *
  31843. * For more information, please refer to :
  31844. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  31845. */
  31846. function UniformBuffer(engine, data, dynamic) {
  31847. this._engine = engine;
  31848. this._noUBO = !engine.supportsUniformBuffers;
  31849. this._dynamic = dynamic;
  31850. this._data = data || [];
  31851. this._uniformLocations = {};
  31852. this._uniformSizes = {};
  31853. this._uniformLocationPointer = 0;
  31854. this._needSync = false;
  31855. if (this._noUBO) {
  31856. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  31857. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  31858. this.updateFloat = this._updateFloatForEffect;
  31859. this.updateFloat2 = this._updateFloat2ForEffect;
  31860. this.updateFloat3 = this._updateFloat3ForEffect;
  31861. this.updateFloat4 = this._updateFloat4ForEffect;
  31862. this.updateMatrix = this._updateMatrixForEffect;
  31863. this.updateVector3 = this._updateVector3ForEffect;
  31864. this.updateVector4 = this._updateVector4ForEffect;
  31865. this.updateColor3 = this._updateColor3ForEffect;
  31866. this.updateColor4 = this._updateColor4ForEffect;
  31867. }
  31868. else {
  31869. this._engine._uniformBuffers.push(this);
  31870. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  31871. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  31872. this.updateFloat = this._updateFloatForUniform;
  31873. this.updateFloat2 = this._updateFloat2ForUniform;
  31874. this.updateFloat3 = this._updateFloat3ForUniform;
  31875. this.updateFloat4 = this._updateFloat4ForUniform;
  31876. this.updateMatrix = this._updateMatrixForUniform;
  31877. this.updateVector3 = this._updateVector3ForUniform;
  31878. this.updateVector4 = this._updateVector4ForUniform;
  31879. this.updateColor3 = this._updateColor3ForUniform;
  31880. this.updateColor4 = this._updateColor4ForUniform;
  31881. }
  31882. }
  31883. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  31884. // Properties
  31885. /**
  31886. * Indicates if the buffer is using the WebGL2 UBO implementation,
  31887. * or just falling back on setUniformXXX calls.
  31888. */
  31889. get: function () {
  31890. return !this._noUBO;
  31891. },
  31892. enumerable: true,
  31893. configurable: true
  31894. });
  31895. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  31896. /**
  31897. * Indicates if the WebGL underlying uniform buffer is in sync
  31898. * with the javascript cache data.
  31899. */
  31900. get: function () {
  31901. return !this._needSync;
  31902. },
  31903. enumerable: true,
  31904. configurable: true
  31905. });
  31906. /**
  31907. * Indicates if the WebGL underlying uniform buffer is dynamic.
  31908. * Also, a dynamic UniformBuffer will disable cache verification and always
  31909. * update the underlying WebGL uniform buffer to the GPU.
  31910. */
  31911. UniformBuffer.prototype.isDynamic = function () {
  31912. return this._dynamic !== undefined;
  31913. };
  31914. /**
  31915. * The data cache on JS side.
  31916. */
  31917. UniformBuffer.prototype.getData = function () {
  31918. return this._bufferData;
  31919. };
  31920. /**
  31921. * The underlying WebGL Uniform buffer.
  31922. */
  31923. UniformBuffer.prototype.getBuffer = function () {
  31924. return this._buffer;
  31925. };
  31926. /**
  31927. * std140 layout specifies how to align data within an UBO structure.
  31928. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  31929. * for specs.
  31930. */
  31931. UniformBuffer.prototype._fillAlignment = function (size) {
  31932. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  31933. // and 4x4 matrices
  31934. // TODO : change if other types are used
  31935. var alignment;
  31936. if (size <= 2) {
  31937. alignment = size;
  31938. }
  31939. else {
  31940. alignment = 4;
  31941. }
  31942. if ((this._uniformLocationPointer % alignment) !== 0) {
  31943. var oldPointer = this._uniformLocationPointer;
  31944. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  31945. var diff = this._uniformLocationPointer - oldPointer;
  31946. for (var i = 0; i < diff; i++) {
  31947. this._data.push(0);
  31948. }
  31949. }
  31950. };
  31951. /**
  31952. * Adds an uniform in the buffer.
  31953. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  31954. * for the layout to be correct !
  31955. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31956. * @param {number|number[]} size Data size, or data directly.
  31957. */
  31958. UniformBuffer.prototype.addUniform = function (name, size) {
  31959. if (this._noUBO) {
  31960. return;
  31961. }
  31962. if (this._uniformLocations[name] !== undefined) {
  31963. // Already existing uniform
  31964. return;
  31965. }
  31966. // This function must be called in the order of the shader layout !
  31967. // size can be the size of the uniform, or data directly
  31968. var data;
  31969. if (size instanceof Array) {
  31970. data = size;
  31971. size = data.length;
  31972. }
  31973. else {
  31974. size = size;
  31975. data = [];
  31976. // Fill with zeros
  31977. for (var i = 0; i < size; i++) {
  31978. data.push(0);
  31979. }
  31980. }
  31981. this._fillAlignment(size);
  31982. this._uniformSizes[name] = size;
  31983. this._uniformLocations[name] = this._uniformLocationPointer;
  31984. this._uniformLocationPointer += size;
  31985. for (var i = 0; i < size; i++) {
  31986. this._data.push(data[i]);
  31987. }
  31988. this._needSync = true;
  31989. };
  31990. /**
  31991. * Wrapper for addUniform.
  31992. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31993. * @param {Matrix} mat A 4x4 matrix.
  31994. */
  31995. UniformBuffer.prototype.addMatrix = function (name, mat) {
  31996. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  31997. };
  31998. /**
  31999. * Wrapper for addUniform.
  32000. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32001. * @param {number} x
  32002. * @param {number} y
  32003. */
  32004. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  32005. var temp = [x, y];
  32006. this.addUniform(name, temp);
  32007. };
  32008. /**
  32009. * Wrapper for addUniform.
  32010. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32011. * @param {number} x
  32012. * @param {number} y
  32013. * @param {number} z
  32014. */
  32015. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  32016. var temp = [x, y, z];
  32017. this.addUniform(name, temp);
  32018. };
  32019. /**
  32020. * Wrapper for addUniform.
  32021. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32022. * @param {Color3} color
  32023. */
  32024. UniformBuffer.prototype.addColor3 = function (name, color) {
  32025. var temp = new Array();
  32026. color.toArray(temp);
  32027. this.addUniform(name, temp);
  32028. };
  32029. /**
  32030. * Wrapper for addUniform.
  32031. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32032. * @param {Color3} color
  32033. * @param {number} alpha
  32034. */
  32035. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  32036. var temp = new Array();
  32037. color.toArray(temp);
  32038. temp.push(alpha);
  32039. this.addUniform(name, temp);
  32040. };
  32041. /**
  32042. * Wrapper for addUniform.
  32043. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32044. * @param {Vector3} vector
  32045. */
  32046. UniformBuffer.prototype.addVector3 = function (name, vector) {
  32047. var temp = new Array();
  32048. vector.toArray(temp);
  32049. this.addUniform(name, temp);
  32050. };
  32051. /**
  32052. * Wrapper for addUniform.
  32053. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32054. */
  32055. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  32056. this.addUniform(name, 12);
  32057. };
  32058. /**
  32059. * Wrapper for addUniform.
  32060. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32061. */
  32062. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  32063. this.addUniform(name, 8);
  32064. };
  32065. /**
  32066. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  32067. */
  32068. UniformBuffer.prototype.create = function () {
  32069. if (this._noUBO) {
  32070. return;
  32071. }
  32072. if (this._buffer) {
  32073. return; // nothing to do
  32074. }
  32075. // See spec, alignment must be filled as a vec4
  32076. this._fillAlignment(4);
  32077. this._bufferData = new Float32Array(this._data);
  32078. this._rebuild();
  32079. this._needSync = true;
  32080. };
  32081. UniformBuffer.prototype._rebuild = function () {
  32082. if (this._noUBO) {
  32083. return;
  32084. }
  32085. if (this._dynamic) {
  32086. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32087. }
  32088. else {
  32089. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32090. }
  32091. };
  32092. /**
  32093. * Updates the WebGL Uniform Buffer on the GPU.
  32094. * If the `dynamic` flag is set to true, no cache comparison is done.
  32095. * Otherwise, the buffer will be updated only if the cache differs.
  32096. */
  32097. UniformBuffer.prototype.update = function () {
  32098. if (!this._buffer) {
  32099. this.create();
  32100. return;
  32101. }
  32102. if (!this._dynamic && !this._needSync) {
  32103. return;
  32104. }
  32105. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32106. this._needSync = false;
  32107. };
  32108. /**
  32109. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32110. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32111. * @param {number[]|Float32Array} data Flattened data
  32112. * @param {number} size Size of the data.
  32113. */
  32114. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32115. var location = this._uniformLocations[uniformName];
  32116. if (location === undefined) {
  32117. if (this._buffer) {
  32118. // Cannot add an uniform if the buffer is already created
  32119. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32120. return;
  32121. }
  32122. this.addUniform(uniformName, size);
  32123. location = this._uniformLocations[uniformName];
  32124. }
  32125. if (!this._buffer) {
  32126. this.create();
  32127. }
  32128. if (!this._dynamic) {
  32129. // Cache for static uniform buffers
  32130. var changed = false;
  32131. for (var i = 0; i < size; i++) {
  32132. if (this._bufferData[location + i] !== data[i]) {
  32133. changed = true;
  32134. this._bufferData[location + i] = data[i];
  32135. }
  32136. }
  32137. this._needSync = this._needSync || changed;
  32138. }
  32139. else {
  32140. // No cache for dynamic
  32141. for (var i = 0; i < size; i++) {
  32142. this._bufferData[location + i] = data[i];
  32143. }
  32144. }
  32145. };
  32146. // Update methods
  32147. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32148. // To match std140, matrix must be realigned
  32149. for (var i = 0; i < 3; i++) {
  32150. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32151. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32152. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32153. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32154. }
  32155. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32156. };
  32157. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32158. this._currentEffect.setMatrix3x3(name, matrix);
  32159. };
  32160. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32161. this._currentEffect.setMatrix2x2(name, matrix);
  32162. };
  32163. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32164. // To match std140, matrix must be realigned
  32165. for (var i = 0; i < 2; i++) {
  32166. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32167. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32168. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32169. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32170. }
  32171. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32172. };
  32173. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32174. this._currentEffect.setFloat(name, x);
  32175. };
  32176. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32177. UniformBuffer._tempBuffer[0] = x;
  32178. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32179. };
  32180. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32181. if (suffix === void 0) { suffix = ""; }
  32182. this._currentEffect.setFloat2(name + suffix, x, y);
  32183. };
  32184. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32185. if (suffix === void 0) { suffix = ""; }
  32186. UniformBuffer._tempBuffer[0] = x;
  32187. UniformBuffer._tempBuffer[1] = y;
  32188. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32189. };
  32190. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32191. if (suffix === void 0) { suffix = ""; }
  32192. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32193. };
  32194. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32195. if (suffix === void 0) { suffix = ""; }
  32196. UniformBuffer._tempBuffer[0] = x;
  32197. UniformBuffer._tempBuffer[1] = y;
  32198. UniformBuffer._tempBuffer[2] = z;
  32199. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32200. };
  32201. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32202. if (suffix === void 0) { suffix = ""; }
  32203. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32204. };
  32205. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32206. if (suffix === void 0) { suffix = ""; }
  32207. UniformBuffer._tempBuffer[0] = x;
  32208. UniformBuffer._tempBuffer[1] = y;
  32209. UniformBuffer._tempBuffer[2] = z;
  32210. UniformBuffer._tempBuffer[3] = w;
  32211. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32212. };
  32213. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32214. this._currentEffect.setMatrix(name, mat);
  32215. };
  32216. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32217. this.updateUniform(name, mat.toArray(), 16);
  32218. };
  32219. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32220. this._currentEffect.setVector3(name, vector);
  32221. };
  32222. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32223. vector.toArray(UniformBuffer._tempBuffer);
  32224. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32225. };
  32226. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32227. this._currentEffect.setVector4(name, vector);
  32228. };
  32229. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32230. vector.toArray(UniformBuffer._tempBuffer);
  32231. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32232. };
  32233. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32234. if (suffix === void 0) { suffix = ""; }
  32235. this._currentEffect.setColor3(name + suffix, color);
  32236. };
  32237. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32238. if (suffix === void 0) { suffix = ""; }
  32239. color.toArray(UniformBuffer._tempBuffer);
  32240. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32241. };
  32242. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32243. if (suffix === void 0) { suffix = ""; }
  32244. this._currentEffect.setColor4(name + suffix, color, alpha);
  32245. };
  32246. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32247. if (suffix === void 0) { suffix = ""; }
  32248. color.toArray(UniformBuffer._tempBuffer);
  32249. UniformBuffer._tempBuffer[3] = alpha;
  32250. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32251. };
  32252. /**
  32253. * Sets a sampler uniform on the effect.
  32254. * @param {string} name Name of the sampler.
  32255. * @param {Texture} texture
  32256. */
  32257. UniformBuffer.prototype.setTexture = function (name, texture) {
  32258. this._currentEffect.setTexture(name, texture);
  32259. };
  32260. /**
  32261. * Directly updates the value of the uniform in the cache AND on the GPU.
  32262. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32263. * @param {number[]|Float32Array} data Flattened data
  32264. */
  32265. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32266. this.updateUniform(uniformName, data, data.length);
  32267. this.update();
  32268. };
  32269. /**
  32270. * Binds this uniform buffer to an effect.
  32271. * @param {Effect} effect
  32272. * @param {string} name Name of the uniform block in the shader.
  32273. */
  32274. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32275. this._currentEffect = effect;
  32276. if (this._noUBO || !this._buffer) {
  32277. return;
  32278. }
  32279. effect.bindUniformBuffer(this._buffer, name);
  32280. };
  32281. /**
  32282. * Disposes the uniform buffer.
  32283. */
  32284. UniformBuffer.prototype.dispose = function () {
  32285. if (this._noUBO) {
  32286. return;
  32287. }
  32288. var index = this._engine._uniformBuffers.indexOf(this);
  32289. if (index !== -1) {
  32290. this._engine._uniformBuffers.splice(index, 1);
  32291. }
  32292. if (!this._buffer) {
  32293. return;
  32294. }
  32295. if (this._engine._releaseBuffer(this._buffer)) {
  32296. this._buffer = null;
  32297. }
  32298. };
  32299. // Pool for avoiding memory leaks
  32300. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32301. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32302. return UniformBuffer;
  32303. }());
  32304. BABYLON.UniformBuffer = UniformBuffer;
  32305. })(BABYLON || (BABYLON = {}));
  32306. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32307. var BABYLON;
  32308. (function (BABYLON) {
  32309. var VertexData = /** @class */ (function () {
  32310. function VertexData() {
  32311. }
  32312. VertexData.prototype.set = function (data, kind) {
  32313. switch (kind) {
  32314. case BABYLON.VertexBuffer.PositionKind:
  32315. this.positions = data;
  32316. break;
  32317. case BABYLON.VertexBuffer.NormalKind:
  32318. this.normals = data;
  32319. break;
  32320. case BABYLON.VertexBuffer.TangentKind:
  32321. this.tangents = data;
  32322. break;
  32323. case BABYLON.VertexBuffer.UVKind:
  32324. this.uvs = data;
  32325. break;
  32326. case BABYLON.VertexBuffer.UV2Kind:
  32327. this.uvs2 = data;
  32328. break;
  32329. case BABYLON.VertexBuffer.UV3Kind:
  32330. this.uvs3 = data;
  32331. break;
  32332. case BABYLON.VertexBuffer.UV4Kind:
  32333. this.uvs4 = data;
  32334. break;
  32335. case BABYLON.VertexBuffer.UV5Kind:
  32336. this.uvs5 = data;
  32337. break;
  32338. case BABYLON.VertexBuffer.UV6Kind:
  32339. this.uvs6 = data;
  32340. break;
  32341. case BABYLON.VertexBuffer.ColorKind:
  32342. this.colors = data;
  32343. break;
  32344. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32345. this.matricesIndices = data;
  32346. break;
  32347. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32348. this.matricesWeights = data;
  32349. break;
  32350. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32351. this.matricesIndicesExtra = data;
  32352. break;
  32353. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32354. this.matricesWeightsExtra = data;
  32355. break;
  32356. }
  32357. };
  32358. /**
  32359. * Associates the vertexData to the passed Mesh.
  32360. * Sets it as updatable or not (default `false`).
  32361. * Returns the VertexData.
  32362. */
  32363. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32364. this._applyTo(mesh, updatable);
  32365. return this;
  32366. };
  32367. /**
  32368. * Associates the vertexData to the passed Geometry.
  32369. * Sets it as updatable or not (default `false`).
  32370. * Returns the VertexData.
  32371. */
  32372. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32373. this._applyTo(geometry, updatable);
  32374. return this;
  32375. };
  32376. /**
  32377. * Updates the associated mesh.
  32378. * Returns the VertexData.
  32379. */
  32380. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32381. this._update(mesh);
  32382. return this;
  32383. };
  32384. /**
  32385. * Updates the associated geometry.
  32386. * Returns the VertexData.
  32387. */
  32388. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32389. this._update(geometry);
  32390. return this;
  32391. };
  32392. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32393. if (updatable === void 0) { updatable = false; }
  32394. if (this.positions) {
  32395. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32396. }
  32397. if (this.normals) {
  32398. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32399. }
  32400. if (this.tangents) {
  32401. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  32402. }
  32403. if (this.uvs) {
  32404. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32405. }
  32406. if (this.uvs2) {
  32407. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32408. }
  32409. if (this.uvs3) {
  32410. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32411. }
  32412. if (this.uvs4) {
  32413. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32414. }
  32415. if (this.uvs5) {
  32416. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32417. }
  32418. if (this.uvs6) {
  32419. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32420. }
  32421. if (this.colors) {
  32422. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32423. }
  32424. if (this.matricesIndices) {
  32425. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32426. }
  32427. if (this.matricesWeights) {
  32428. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32429. }
  32430. if (this.matricesIndicesExtra) {
  32431. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32432. }
  32433. if (this.matricesWeightsExtra) {
  32434. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32435. }
  32436. if (this.indices) {
  32437. meshOrGeometry.setIndices(this.indices, null, updatable);
  32438. }
  32439. return this;
  32440. };
  32441. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32442. if (this.positions) {
  32443. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32444. }
  32445. if (this.normals) {
  32446. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32447. }
  32448. if (this.tangents) {
  32449. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  32450. }
  32451. if (this.uvs) {
  32452. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32453. }
  32454. if (this.uvs2) {
  32455. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32456. }
  32457. if (this.uvs3) {
  32458. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32459. }
  32460. if (this.uvs4) {
  32461. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32462. }
  32463. if (this.uvs5) {
  32464. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32465. }
  32466. if (this.uvs6) {
  32467. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32468. }
  32469. if (this.colors) {
  32470. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32471. }
  32472. if (this.matricesIndices) {
  32473. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  32474. }
  32475. if (this.matricesWeights) {
  32476. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  32477. }
  32478. if (this.matricesIndicesExtra) {
  32479. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  32480. }
  32481. if (this.matricesWeightsExtra) {
  32482. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  32483. }
  32484. if (this.indices) {
  32485. meshOrGeometry.setIndices(this.indices, null);
  32486. }
  32487. return this;
  32488. };
  32489. /**
  32490. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  32491. * Returns the VertexData.
  32492. */
  32493. VertexData.prototype.transform = function (matrix) {
  32494. var transformed = BABYLON.Vector3.Zero();
  32495. var index;
  32496. if (this.positions) {
  32497. var position = BABYLON.Vector3.Zero();
  32498. for (index = 0; index < this.positions.length; index += 3) {
  32499. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  32500. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  32501. this.positions[index] = transformed.x;
  32502. this.positions[index + 1] = transformed.y;
  32503. this.positions[index + 2] = transformed.z;
  32504. }
  32505. }
  32506. if (this.normals) {
  32507. var normal = BABYLON.Vector3.Zero();
  32508. for (index = 0; index < this.normals.length; index += 3) {
  32509. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  32510. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  32511. this.normals[index] = transformed.x;
  32512. this.normals[index + 1] = transformed.y;
  32513. this.normals[index + 2] = transformed.z;
  32514. }
  32515. }
  32516. if (this.tangents) {
  32517. var tangent = BABYLON.Vector4.Zero();
  32518. var tangentTransformed = BABYLON.Vector4.Zero();
  32519. for (index = 0; index < this.tangents.length; index += 4) {
  32520. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  32521. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  32522. this.tangents[index] = tangentTransformed.x;
  32523. this.tangents[index + 1] = tangentTransformed.y;
  32524. this.tangents[index + 2] = tangentTransformed.z;
  32525. this.tangents[index + 3] = tangentTransformed.w;
  32526. }
  32527. }
  32528. return this;
  32529. };
  32530. /**
  32531. * Merges the passed VertexData into the current one.
  32532. * Returns the modified VertexData.
  32533. */
  32534. VertexData.prototype.merge = function (other) {
  32535. this._validate();
  32536. other._validate();
  32537. if (!this.normals !== !other.normals ||
  32538. !this.tangents !== !other.tangents ||
  32539. !this.uvs !== !other.uvs ||
  32540. !this.uvs2 !== !other.uvs2 ||
  32541. !this.uvs3 !== !other.uvs3 ||
  32542. !this.uvs4 !== !other.uvs4 ||
  32543. !this.uvs5 !== !other.uvs5 ||
  32544. !this.uvs6 !== !other.uvs6 ||
  32545. !this.colors !== !other.colors ||
  32546. !this.matricesIndices !== !other.matricesIndices ||
  32547. !this.matricesWeights !== !other.matricesWeights ||
  32548. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  32549. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  32550. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  32551. }
  32552. if (other.indices) {
  32553. if (!this.indices) {
  32554. this.indices = [];
  32555. }
  32556. var offset = this.positions ? this.positions.length / 3 : 0;
  32557. for (var index = 0; index < other.indices.length; index++) {
  32558. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  32559. this.indices.push(other.indices[index] + offset);
  32560. }
  32561. }
  32562. this.positions = this._mergeElement(this.positions, other.positions);
  32563. this.normals = this._mergeElement(this.normals, other.normals);
  32564. this.tangents = this._mergeElement(this.tangents, other.tangents);
  32565. this.uvs = this._mergeElement(this.uvs, other.uvs);
  32566. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  32567. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  32568. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  32569. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  32570. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  32571. this.colors = this._mergeElement(this.colors, other.colors);
  32572. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  32573. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  32574. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  32575. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32576. return this;
  32577. };
  32578. VertexData.prototype._mergeElement = function (source, other) {
  32579. if (!source) {
  32580. return other;
  32581. }
  32582. if (!other) {
  32583. return source;
  32584. }
  32585. var len = other.length + source.length;
  32586. var isSrcTypedArray = source instanceof Float32Array;
  32587. var isOthTypedArray = other instanceof Float32Array;
  32588. // use non-loop method when the source is Float32Array
  32589. if (isSrcTypedArray) {
  32590. var ret32 = new Float32Array(len);
  32591. ret32.set(source);
  32592. ret32.set(other, source.length);
  32593. return ret32;
  32594. // source is number[], when other is also use concat
  32595. }
  32596. else if (!isOthTypedArray) {
  32597. return source.concat(other);
  32598. // source is a number[], but other is a Float32Array, loop required
  32599. }
  32600. else {
  32601. var ret = source.slice(0); // copy source to a separate array
  32602. for (var i = 0, len = other.length; i < len; i++) {
  32603. ret.push(other[i]);
  32604. }
  32605. return ret;
  32606. }
  32607. };
  32608. VertexData.prototype._validate = function () {
  32609. if (!this.positions) {
  32610. throw new Error("Positions are required");
  32611. }
  32612. var getElementCount = function (kind, values) {
  32613. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  32614. if ((values.length % stride) !== 0) {
  32615. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  32616. }
  32617. return values.length / stride;
  32618. };
  32619. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  32620. var validateElementCount = function (kind, values) {
  32621. var elementCount = getElementCount(kind, values);
  32622. if (elementCount !== positionsElementCount) {
  32623. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  32624. }
  32625. };
  32626. if (this.normals)
  32627. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  32628. if (this.tangents)
  32629. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  32630. if (this.uvs)
  32631. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  32632. if (this.uvs2)
  32633. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  32634. if (this.uvs3)
  32635. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  32636. if (this.uvs4)
  32637. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  32638. if (this.uvs5)
  32639. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  32640. if (this.uvs6)
  32641. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  32642. if (this.colors)
  32643. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  32644. if (this.matricesIndices)
  32645. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  32646. if (this.matricesWeights)
  32647. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  32648. if (this.matricesIndicesExtra)
  32649. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  32650. if (this.matricesWeightsExtra)
  32651. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  32652. };
  32653. /**
  32654. * Serializes the VertexData.
  32655. * Returns a serialized object.
  32656. */
  32657. VertexData.prototype.serialize = function () {
  32658. var serializationObject = this.serialize();
  32659. if (this.positions) {
  32660. serializationObject.positions = this.positions;
  32661. }
  32662. if (this.normals) {
  32663. serializationObject.normals = this.normals;
  32664. }
  32665. if (this.tangents) {
  32666. serializationObject.tangents = this.tangents;
  32667. }
  32668. if (this.uvs) {
  32669. serializationObject.uvs = this.uvs;
  32670. }
  32671. if (this.uvs2) {
  32672. serializationObject.uvs2 = this.uvs2;
  32673. }
  32674. if (this.uvs3) {
  32675. serializationObject.uvs3 = this.uvs3;
  32676. }
  32677. if (this.uvs4) {
  32678. serializationObject.uvs4 = this.uvs4;
  32679. }
  32680. if (this.uvs5) {
  32681. serializationObject.uvs5 = this.uvs5;
  32682. }
  32683. if (this.uvs6) {
  32684. serializationObject.uvs6 = this.uvs6;
  32685. }
  32686. if (this.colors) {
  32687. serializationObject.colors = this.colors;
  32688. }
  32689. if (this.matricesIndices) {
  32690. serializationObject.matricesIndices = this.matricesIndices;
  32691. serializationObject.matricesIndices._isExpanded = true;
  32692. }
  32693. if (this.matricesWeights) {
  32694. serializationObject.matricesWeights = this.matricesWeights;
  32695. }
  32696. if (this.matricesIndicesExtra) {
  32697. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32698. serializationObject.matricesIndicesExtra._isExpanded = true;
  32699. }
  32700. if (this.matricesWeightsExtra) {
  32701. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32702. }
  32703. serializationObject.indices = this.indices;
  32704. return serializationObject;
  32705. };
  32706. // Statics
  32707. /**
  32708. * Returns the object VertexData associated to the passed mesh.
  32709. */
  32710. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  32711. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  32712. };
  32713. /**
  32714. * Returns the object VertexData associated to the passed geometry.
  32715. */
  32716. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  32717. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  32718. };
  32719. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  32720. var result = new VertexData();
  32721. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32722. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  32723. }
  32724. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32725. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  32726. }
  32727. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32728. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  32729. }
  32730. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32731. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  32732. }
  32733. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32734. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  32735. }
  32736. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32737. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  32738. }
  32739. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32740. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  32741. }
  32742. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32743. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  32744. }
  32745. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32746. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  32747. }
  32748. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32749. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  32750. }
  32751. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32752. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  32753. }
  32754. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32755. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  32756. }
  32757. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32758. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  32759. }
  32760. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32761. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  32762. }
  32763. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32764. return result;
  32765. };
  32766. /**
  32767. * Creates the vertexData of the Ribbon.
  32768. */
  32769. VertexData.CreateRibbon = function (options) {
  32770. var pathArray = options.pathArray;
  32771. var closeArray = options.closeArray || false;
  32772. var closePath = options.closePath || false;
  32773. var invertUV = options.invertUV || false;
  32774. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32775. var offset = options.offset || defaultOffset;
  32776. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32777. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32778. var customUV = options.uvs;
  32779. var customColors = options.colors;
  32780. var positions = [];
  32781. var indices = [];
  32782. var normals = [];
  32783. var uvs = [];
  32784. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32785. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32786. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32787. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32788. var minlg; // minimal length among all paths from pathArray
  32789. var lg = []; // array of path lengths : nb of vertex per path
  32790. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32791. var p; // path iterator
  32792. var i; // point iterator
  32793. var j; // point iterator
  32794. // if single path in pathArray
  32795. if (pathArray.length < 2) {
  32796. var ar1 = [];
  32797. var ar2 = [];
  32798. for (i = 0; i < pathArray[0].length - offset; i++) {
  32799. ar1.push(pathArray[0][i]);
  32800. ar2.push(pathArray[0][i + offset]);
  32801. }
  32802. pathArray = [ar1, ar2];
  32803. }
  32804. // positions and horizontal distances (u)
  32805. var idc = 0;
  32806. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  32807. var path;
  32808. var l;
  32809. minlg = pathArray[0].length;
  32810. var vectlg;
  32811. var dist;
  32812. for (p = 0; p < pathArray.length; p++) {
  32813. uTotalDistance[p] = 0;
  32814. us[p] = [0];
  32815. path = pathArray[p];
  32816. l = path.length;
  32817. minlg = (minlg < l) ? minlg : l;
  32818. j = 0;
  32819. while (j < l) {
  32820. positions.push(path[j].x, path[j].y, path[j].z);
  32821. if (j > 0) {
  32822. vectlg = path[j].subtract(path[j - 1]).length();
  32823. dist = vectlg + uTotalDistance[p];
  32824. us[p].push(dist);
  32825. uTotalDistance[p] = dist;
  32826. }
  32827. j++;
  32828. }
  32829. if (closePath) {
  32830. j--;
  32831. positions.push(path[0].x, path[0].y, path[0].z);
  32832. vectlg = path[j].subtract(path[0]).length();
  32833. dist = vectlg + uTotalDistance[p];
  32834. us[p].push(dist);
  32835. uTotalDistance[p] = dist;
  32836. }
  32837. lg[p] = l + closePathCorr;
  32838. idx[p] = idc;
  32839. idc += (l + closePathCorr);
  32840. }
  32841. // vertical distances (v)
  32842. var path1;
  32843. var path2;
  32844. var vertex1 = null;
  32845. var vertex2 = null;
  32846. for (i = 0; i < minlg + closePathCorr; i++) {
  32847. vTotalDistance[i] = 0;
  32848. vs[i] = [0];
  32849. for (p = 0; p < pathArray.length - 1; p++) {
  32850. path1 = pathArray[p];
  32851. path2 = pathArray[p + 1];
  32852. if (i === minlg) {
  32853. vertex1 = path1[0];
  32854. vertex2 = path2[0];
  32855. }
  32856. else {
  32857. vertex1 = path1[i];
  32858. vertex2 = path2[i];
  32859. }
  32860. vectlg = vertex2.subtract(vertex1).length();
  32861. dist = vectlg + vTotalDistance[i];
  32862. vs[i].push(dist);
  32863. vTotalDistance[i] = dist;
  32864. }
  32865. if (closeArray && vertex2 && vertex1) {
  32866. path1 = pathArray[p];
  32867. path2 = pathArray[0];
  32868. if (i === minlg) {
  32869. vertex2 = path2[0];
  32870. }
  32871. vectlg = vertex2.subtract(vertex1).length();
  32872. dist = vectlg + vTotalDistance[i];
  32873. vTotalDistance[i] = dist;
  32874. }
  32875. }
  32876. // uvs
  32877. var u;
  32878. var v;
  32879. if (customUV) {
  32880. for (p = 0; p < customUV.length; p++) {
  32881. uvs.push(customUV[p].x, customUV[p].y);
  32882. }
  32883. }
  32884. else {
  32885. for (p = 0; p < pathArray.length; p++) {
  32886. for (i = 0; i < minlg + closePathCorr; i++) {
  32887. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  32888. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  32889. if (invertUV) {
  32890. uvs.push(v, u);
  32891. }
  32892. else {
  32893. uvs.push(u, v);
  32894. }
  32895. }
  32896. }
  32897. }
  32898. // indices
  32899. p = 0; // path index
  32900. var pi = 0; // positions array index
  32901. var l1 = lg[p] - 1; // path1 length
  32902. var l2 = lg[p + 1] - 1; // path2 length
  32903. var min = (l1 < l2) ? l1 : l2; // current path stop index
  32904. var shft = idx[1] - idx[0]; // shift
  32905. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  32906. while (pi <= min && p < path1nb) {
  32907. // 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
  32908. indices.push(pi, pi + shft, pi + 1);
  32909. indices.push(pi + shft + 1, pi + 1, pi + shft);
  32910. pi += 1;
  32911. if (pi === min) {
  32912. p++;
  32913. if (p === lg.length - 1) {
  32914. shft = idx[0] - idx[p];
  32915. l1 = lg[p] - 1;
  32916. l2 = lg[0] - 1;
  32917. }
  32918. else {
  32919. shft = idx[p + 1] - idx[p];
  32920. l1 = lg[p] - 1;
  32921. l2 = lg[p + 1] - 1;
  32922. }
  32923. pi = idx[p];
  32924. min = (l1 < l2) ? l1 + pi : l2 + pi;
  32925. }
  32926. }
  32927. // normals
  32928. VertexData.ComputeNormals(positions, indices, normals);
  32929. if (closePath) {
  32930. var indexFirst = 0;
  32931. var indexLast = 0;
  32932. for (p = 0; p < pathArray.length; p++) {
  32933. indexFirst = idx[p] * 3;
  32934. if (p + 1 < pathArray.length) {
  32935. indexLast = (idx[p + 1] - 1) * 3;
  32936. }
  32937. else {
  32938. indexLast = normals.length - 3;
  32939. }
  32940. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  32941. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  32942. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  32943. normals[indexLast] = normals[indexFirst];
  32944. normals[indexLast + 1] = normals[indexFirst + 1];
  32945. normals[indexLast + 2] = normals[indexFirst + 2];
  32946. }
  32947. }
  32948. // sides
  32949. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32950. // Colors
  32951. var colors = null;
  32952. if (customColors) {
  32953. colors = new Float32Array(customColors.length * 4);
  32954. for (var c = 0; c < customColors.length; c++) {
  32955. colors[c * 4] = customColors[c].r;
  32956. colors[c * 4 + 1] = customColors[c].g;
  32957. colors[c * 4 + 2] = customColors[c].b;
  32958. colors[c * 4 + 3] = customColors[c].a;
  32959. }
  32960. }
  32961. // Result
  32962. var vertexData = new VertexData();
  32963. var positions32 = new Float32Array(positions);
  32964. var normals32 = new Float32Array(normals);
  32965. var uvs32 = new Float32Array(uvs);
  32966. vertexData.indices = indices;
  32967. vertexData.positions = positions32;
  32968. vertexData.normals = normals32;
  32969. vertexData.uvs = uvs32;
  32970. if (colors) {
  32971. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  32972. }
  32973. if (closePath) {
  32974. vertexData._idx = idx;
  32975. }
  32976. return vertexData;
  32977. };
  32978. /**
  32979. * Creates the VertexData of the Box.
  32980. */
  32981. VertexData.CreateBox = function (options) {
  32982. var normalsSource = [
  32983. new BABYLON.Vector3(0, 0, 1),
  32984. new BABYLON.Vector3(0, 0, -1),
  32985. new BABYLON.Vector3(1, 0, 0),
  32986. new BABYLON.Vector3(-1, 0, 0),
  32987. new BABYLON.Vector3(0, 1, 0),
  32988. new BABYLON.Vector3(0, -1, 0)
  32989. ];
  32990. var indices = [];
  32991. var positions = [];
  32992. var normals = [];
  32993. var uvs = [];
  32994. var width = options.width || options.size || 1;
  32995. var height = options.height || options.size || 1;
  32996. var depth = options.depth || options.size || 1;
  32997. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32998. var faceUV = options.faceUV || new Array(6);
  32999. var faceColors = options.faceColors;
  33000. var colors = [];
  33001. // default face colors and UV if undefined
  33002. for (var f = 0; f < 6; f++) {
  33003. if (faceUV[f] === undefined) {
  33004. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33005. }
  33006. if (faceColors && faceColors[f] === undefined) {
  33007. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33008. }
  33009. }
  33010. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  33011. // Create each face in turn.
  33012. for (var index = 0; index < normalsSource.length; index++) {
  33013. var normal = normalsSource[index];
  33014. // Get two vectors perpendicular to the face normal and to each other.
  33015. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  33016. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33017. // Six indices (two triangles) per face.
  33018. var verticesLength = positions.length / 3;
  33019. indices.push(verticesLength);
  33020. indices.push(verticesLength + 1);
  33021. indices.push(verticesLength + 2);
  33022. indices.push(verticesLength);
  33023. indices.push(verticesLength + 2);
  33024. indices.push(verticesLength + 3);
  33025. // Four vertices per face.
  33026. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33027. positions.push(vertex.x, vertex.y, vertex.z);
  33028. normals.push(normal.x, normal.y, normal.z);
  33029. uvs.push(faceUV[index].z, faceUV[index].w);
  33030. if (faceColors) {
  33031. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33032. }
  33033. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33034. positions.push(vertex.x, vertex.y, vertex.z);
  33035. normals.push(normal.x, normal.y, normal.z);
  33036. uvs.push(faceUV[index].x, faceUV[index].w);
  33037. if (faceColors) {
  33038. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33039. }
  33040. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33041. positions.push(vertex.x, vertex.y, vertex.z);
  33042. normals.push(normal.x, normal.y, normal.z);
  33043. uvs.push(faceUV[index].x, faceUV[index].y);
  33044. if (faceColors) {
  33045. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33046. }
  33047. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33048. positions.push(vertex.x, vertex.y, vertex.z);
  33049. normals.push(normal.x, normal.y, normal.z);
  33050. uvs.push(faceUV[index].z, faceUV[index].y);
  33051. if (faceColors) {
  33052. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33053. }
  33054. }
  33055. // sides
  33056. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33057. // Result
  33058. var vertexData = new VertexData();
  33059. vertexData.indices = indices;
  33060. vertexData.positions = positions;
  33061. vertexData.normals = normals;
  33062. vertexData.uvs = uvs;
  33063. if (faceColors) {
  33064. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33065. vertexData.colors = totalColors;
  33066. }
  33067. return vertexData;
  33068. };
  33069. /**
  33070. * Creates the VertexData of the Sphere.
  33071. */
  33072. VertexData.CreateSphere = function (options) {
  33073. var segments = options.segments || 32;
  33074. var diameterX = options.diameterX || options.diameter || 1;
  33075. var diameterY = options.diameterY || options.diameter || 1;
  33076. var diameterZ = options.diameterZ || options.diameter || 1;
  33077. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33078. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33079. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33080. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33081. var totalZRotationSteps = 2 + segments;
  33082. var totalYRotationSteps = 2 * totalZRotationSteps;
  33083. var indices = [];
  33084. var positions = [];
  33085. var normals = [];
  33086. var uvs = [];
  33087. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33088. var normalizedZ = zRotationStep / totalZRotationSteps;
  33089. var angleZ = normalizedZ * Math.PI * slice;
  33090. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33091. var normalizedY = yRotationStep / totalYRotationSteps;
  33092. var angleY = normalizedY * Math.PI * 2 * arc;
  33093. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33094. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33095. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33096. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33097. var vertex = complete.multiply(radius);
  33098. var normal = complete.divide(radius).normalize();
  33099. positions.push(vertex.x, vertex.y, vertex.z);
  33100. normals.push(normal.x, normal.y, normal.z);
  33101. uvs.push(normalizedY, normalizedZ);
  33102. }
  33103. if (zRotationStep > 0) {
  33104. var verticesCount = positions.length / 3;
  33105. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33106. indices.push((firstIndex));
  33107. indices.push((firstIndex + 1));
  33108. indices.push(firstIndex + totalYRotationSteps + 1);
  33109. indices.push((firstIndex + totalYRotationSteps + 1));
  33110. indices.push((firstIndex + 1));
  33111. indices.push((firstIndex + totalYRotationSteps + 2));
  33112. }
  33113. }
  33114. }
  33115. // Sides
  33116. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33117. // Result
  33118. var vertexData = new VertexData();
  33119. vertexData.indices = indices;
  33120. vertexData.positions = positions;
  33121. vertexData.normals = normals;
  33122. vertexData.uvs = uvs;
  33123. return vertexData;
  33124. };
  33125. /**
  33126. * Creates the VertexData of the Cylinder or Cone.
  33127. */
  33128. VertexData.CreateCylinder = function (options) {
  33129. var height = options.height || 2;
  33130. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33131. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33132. var tessellation = options.tessellation || 24;
  33133. var subdivisions = options.subdivisions || 1;
  33134. var hasRings = options.hasRings ? true : false;
  33135. var enclose = options.enclose ? true : false;
  33136. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33137. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33138. var faceUV = options.faceUV || new Array(3);
  33139. var faceColors = options.faceColors;
  33140. // default face colors and UV if undefined
  33141. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33142. var ringNb = (hasRings) ? subdivisions : 1;
  33143. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33144. var f;
  33145. for (f = 0; f < surfaceNb; f++) {
  33146. if (faceColors && faceColors[f] === undefined) {
  33147. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33148. }
  33149. }
  33150. for (f = 0; f < surfaceNb; f++) {
  33151. if (faceUV && faceUV[f] === undefined) {
  33152. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33153. }
  33154. }
  33155. var indices = new Array();
  33156. var positions = new Array();
  33157. var normals = new Array();
  33158. var uvs = new Array();
  33159. var colors = new Array();
  33160. var angle_step = Math.PI * 2 * arc / tessellation;
  33161. var angle;
  33162. var h;
  33163. var radius;
  33164. var tan = (diameterBottom - diameterTop) / 2 / height;
  33165. var ringVertex = BABYLON.Vector3.Zero();
  33166. var ringNormal = BABYLON.Vector3.Zero();
  33167. var ringFirstVertex = BABYLON.Vector3.Zero();
  33168. var ringFirstNormal = BABYLON.Vector3.Zero();
  33169. var quadNormal = BABYLON.Vector3.Zero();
  33170. var Y = BABYLON.Axis.Y;
  33171. // positions, normals, uvs
  33172. var i;
  33173. var j;
  33174. var r;
  33175. var ringIdx = 1;
  33176. var s = 1; // surface index
  33177. var cs = 0;
  33178. var v = 0;
  33179. for (i = 0; i <= subdivisions; i++) {
  33180. h = i / subdivisions;
  33181. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33182. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33183. for (r = 0; r < ringIdx; r++) {
  33184. if (hasRings) {
  33185. s += r;
  33186. }
  33187. if (enclose) {
  33188. s += 2 * r;
  33189. }
  33190. for (j = 0; j <= tessellation; j++) {
  33191. angle = j * angle_step;
  33192. // position
  33193. ringVertex.x = Math.cos(-angle) * radius;
  33194. ringVertex.y = -height / 2 + h * height;
  33195. ringVertex.z = Math.sin(-angle) * radius;
  33196. // normal
  33197. if (diameterTop === 0 && i === subdivisions) {
  33198. // if no top cap, reuse former normals
  33199. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33200. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33201. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33202. }
  33203. else {
  33204. ringNormal.x = ringVertex.x;
  33205. ringNormal.z = ringVertex.z;
  33206. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33207. ringNormal.normalize();
  33208. }
  33209. // keep first ring vertex values for enclose
  33210. if (j === 0) {
  33211. ringFirstVertex.copyFrom(ringVertex);
  33212. ringFirstNormal.copyFrom(ringNormal);
  33213. }
  33214. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33215. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33216. if (hasRings) {
  33217. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33218. }
  33219. else {
  33220. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33221. }
  33222. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33223. if (faceColors) {
  33224. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33225. }
  33226. }
  33227. // if enclose, add four vertices and their dedicated normals
  33228. if (arc !== 1 && enclose) {
  33229. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33230. positions.push(0, ringVertex.y, 0);
  33231. positions.push(0, ringVertex.y, 0);
  33232. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33233. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33234. quadNormal.normalize();
  33235. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33236. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33237. quadNormal.normalize();
  33238. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33239. if (hasRings) {
  33240. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33241. }
  33242. else {
  33243. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33244. }
  33245. uvs.push(faceUV[s + 1].x, v);
  33246. uvs.push(faceUV[s + 1].z, v);
  33247. if (hasRings) {
  33248. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33249. }
  33250. else {
  33251. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33252. }
  33253. uvs.push(faceUV[s + 2].x, v);
  33254. uvs.push(faceUV[s + 2].z, v);
  33255. if (faceColors) {
  33256. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33257. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33258. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33259. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33260. }
  33261. }
  33262. if (cs !== s) {
  33263. cs = s;
  33264. }
  33265. }
  33266. }
  33267. // indices
  33268. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33269. var s;
  33270. i = 0;
  33271. for (s = 0; s < subdivisions; s++) {
  33272. var i0 = 0;
  33273. var i1 = 0;
  33274. var i2 = 0;
  33275. var i3 = 0;
  33276. for (j = 0; j < tessellation; j++) {
  33277. i0 = i * (e + 1) + j;
  33278. i1 = (i + 1) * (e + 1) + j;
  33279. i2 = i * (e + 1) + (j + 1);
  33280. i3 = (i + 1) * (e + 1) + (j + 1);
  33281. indices.push(i0, i1, i2);
  33282. indices.push(i3, i2, i1);
  33283. }
  33284. if (arc !== 1 && enclose) {
  33285. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33286. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33287. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33288. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33289. }
  33290. i = (hasRings) ? (i + 2) : (i + 1);
  33291. }
  33292. // Caps
  33293. var createCylinderCap = function (isTop) {
  33294. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33295. if (radius === 0) {
  33296. return;
  33297. }
  33298. // Cap positions, normals & uvs
  33299. var angle;
  33300. var circleVector;
  33301. var i;
  33302. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33303. var c = null;
  33304. if (faceColors) {
  33305. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33306. }
  33307. // cap center
  33308. var vbase = positions.length / 3;
  33309. var offset = isTop ? height / 2 : -height / 2;
  33310. var center = new BABYLON.Vector3(0, offset, 0);
  33311. positions.push(center.x, center.y, center.z);
  33312. normals.push(0, isTop ? 1 : -1, 0);
  33313. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33314. if (c) {
  33315. colors.push(c.r, c.g, c.b, c.a);
  33316. }
  33317. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33318. for (i = 0; i <= tessellation; i++) {
  33319. angle = Math.PI * 2 * i * arc / tessellation;
  33320. var cos = Math.cos(-angle);
  33321. var sin = Math.sin(-angle);
  33322. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33323. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33324. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33325. normals.push(0, isTop ? 1 : -1, 0);
  33326. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33327. if (c) {
  33328. colors.push(c.r, c.g, c.b, c.a);
  33329. }
  33330. }
  33331. // Cap indices
  33332. for (i = 0; i < tessellation; i++) {
  33333. if (!isTop) {
  33334. indices.push(vbase);
  33335. indices.push(vbase + (i + 1));
  33336. indices.push(vbase + (i + 2));
  33337. }
  33338. else {
  33339. indices.push(vbase);
  33340. indices.push(vbase + (i + 2));
  33341. indices.push(vbase + (i + 1));
  33342. }
  33343. }
  33344. };
  33345. // add caps to geometry
  33346. createCylinderCap(false);
  33347. createCylinderCap(true);
  33348. // Sides
  33349. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33350. var vertexData = new VertexData();
  33351. vertexData.indices = indices;
  33352. vertexData.positions = positions;
  33353. vertexData.normals = normals;
  33354. vertexData.uvs = uvs;
  33355. if (faceColors) {
  33356. vertexData.colors = colors;
  33357. }
  33358. return vertexData;
  33359. };
  33360. /**
  33361. * Creates the VertexData of the Torus.
  33362. */
  33363. VertexData.CreateTorus = function (options) {
  33364. var indices = [];
  33365. var positions = [];
  33366. var normals = [];
  33367. var uvs = [];
  33368. var diameter = options.diameter || 1;
  33369. var thickness = options.thickness || 0.5;
  33370. var tessellation = options.tessellation || 16;
  33371. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33372. var stride = tessellation + 1;
  33373. for (var i = 0; i <= tessellation; i++) {
  33374. var u = i / tessellation;
  33375. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33376. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33377. for (var j = 0; j <= tessellation; j++) {
  33378. var v = 1 - j / tessellation;
  33379. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33380. var dx = Math.cos(innerAngle);
  33381. var dy = Math.sin(innerAngle);
  33382. // Create a vertex.
  33383. var normal = new BABYLON.Vector3(dx, dy, 0);
  33384. var position = normal.scale(thickness / 2);
  33385. var textureCoordinate = new BABYLON.Vector2(u, v);
  33386. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33387. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33388. positions.push(position.x, position.y, position.z);
  33389. normals.push(normal.x, normal.y, normal.z);
  33390. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33391. // And create indices for two triangles.
  33392. var nextI = (i + 1) % stride;
  33393. var nextJ = (j + 1) % stride;
  33394. indices.push(i * stride + j);
  33395. indices.push(i * stride + nextJ);
  33396. indices.push(nextI * stride + j);
  33397. indices.push(i * stride + nextJ);
  33398. indices.push(nextI * stride + nextJ);
  33399. indices.push(nextI * stride + j);
  33400. }
  33401. }
  33402. // Sides
  33403. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33404. // Result
  33405. var vertexData = new VertexData();
  33406. vertexData.indices = indices;
  33407. vertexData.positions = positions;
  33408. vertexData.normals = normals;
  33409. vertexData.uvs = uvs;
  33410. return vertexData;
  33411. };
  33412. /**
  33413. * Creates the VertexData of the LineSystem.
  33414. */
  33415. VertexData.CreateLineSystem = function (options) {
  33416. var indices = [];
  33417. var positions = [];
  33418. var lines = options.lines;
  33419. var colors = options.colors;
  33420. var vertexColors = [];
  33421. var idx = 0;
  33422. for (var l = 0; l < lines.length; l++) {
  33423. var points = lines[l];
  33424. for (var index = 0; index < points.length; index++) {
  33425. positions.push(points[index].x, points[index].y, points[index].z);
  33426. if (colors) {
  33427. var color = colors[l];
  33428. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  33429. }
  33430. if (index > 0) {
  33431. indices.push(idx - 1);
  33432. indices.push(idx);
  33433. }
  33434. idx++;
  33435. }
  33436. }
  33437. var vertexData = new VertexData();
  33438. vertexData.indices = indices;
  33439. vertexData.positions = positions;
  33440. if (colors) {
  33441. vertexData.colors = vertexColors;
  33442. }
  33443. return vertexData;
  33444. };
  33445. /**
  33446. * Create the VertexData of the DashedLines.
  33447. */
  33448. VertexData.CreateDashedLines = function (options) {
  33449. var dashSize = options.dashSize || 3;
  33450. var gapSize = options.gapSize || 1;
  33451. var dashNb = options.dashNb || 200;
  33452. var points = options.points;
  33453. var positions = new Array();
  33454. var indices = new Array();
  33455. var curvect = BABYLON.Vector3.Zero();
  33456. var lg = 0;
  33457. var nb = 0;
  33458. var shft = 0;
  33459. var dashshft = 0;
  33460. var curshft = 0;
  33461. var idx = 0;
  33462. var i = 0;
  33463. for (i = 0; i < points.length - 1; i++) {
  33464. points[i + 1].subtractToRef(points[i], curvect);
  33465. lg += curvect.length();
  33466. }
  33467. shft = lg / dashNb;
  33468. dashshft = dashSize * shft / (dashSize + gapSize);
  33469. for (i = 0; i < points.length - 1; i++) {
  33470. points[i + 1].subtractToRef(points[i], curvect);
  33471. nb = Math.floor(curvect.length() / shft);
  33472. curvect.normalize();
  33473. for (var j = 0; j < nb; j++) {
  33474. curshft = shft * j;
  33475. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  33476. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  33477. indices.push(idx, idx + 1);
  33478. idx += 2;
  33479. }
  33480. }
  33481. // Result
  33482. var vertexData = new VertexData();
  33483. vertexData.positions = positions;
  33484. vertexData.indices = indices;
  33485. return vertexData;
  33486. };
  33487. /**
  33488. * Creates the VertexData of the Ground.
  33489. */
  33490. VertexData.CreateGround = function (options) {
  33491. var indices = [];
  33492. var positions = [];
  33493. var normals = [];
  33494. var uvs = [];
  33495. var row, col;
  33496. var width = options.width || 1;
  33497. var height = options.height || 1;
  33498. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  33499. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  33500. for (row = 0; row <= subdivisionsY; row++) {
  33501. for (col = 0; col <= subdivisionsX; col++) {
  33502. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  33503. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33504. positions.push(position.x, position.y, position.z);
  33505. normals.push(normal.x, normal.y, normal.z);
  33506. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  33507. }
  33508. }
  33509. for (row = 0; row < subdivisionsY; row++) {
  33510. for (col = 0; col < subdivisionsX; col++) {
  33511. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33512. indices.push(col + 1 + row * (subdivisionsX + 1));
  33513. indices.push(col + row * (subdivisionsX + 1));
  33514. indices.push(col + (row + 1) * (subdivisionsX + 1));
  33515. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33516. indices.push(col + row * (subdivisionsX + 1));
  33517. }
  33518. }
  33519. // Result
  33520. var vertexData = new VertexData();
  33521. vertexData.indices = indices;
  33522. vertexData.positions = positions;
  33523. vertexData.normals = normals;
  33524. vertexData.uvs = uvs;
  33525. return vertexData;
  33526. };
  33527. /**
  33528. * Creates the VertexData of the TiledGround.
  33529. */
  33530. VertexData.CreateTiledGround = function (options) {
  33531. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  33532. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  33533. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  33534. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  33535. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  33536. var precision = options.precision || { w: 1, h: 1 };
  33537. var indices = new Array();
  33538. var positions = new Array();
  33539. var normals = new Array();
  33540. var uvs = new Array();
  33541. var row, col, tileRow, tileCol;
  33542. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  33543. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  33544. precision.w = (precision.w < 1) ? 1 : precision.w;
  33545. precision.h = (precision.h < 1) ? 1 : precision.h;
  33546. var tileSize = {
  33547. 'w': (xmax - xmin) / subdivisions.w,
  33548. 'h': (zmax - zmin) / subdivisions.h
  33549. };
  33550. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  33551. // Indices
  33552. var base = positions.length / 3;
  33553. var rowLength = precision.w + 1;
  33554. for (row = 0; row < precision.h; row++) {
  33555. for (col = 0; col < precision.w; col++) {
  33556. var square = [
  33557. base + col + row * rowLength,
  33558. base + (col + 1) + row * rowLength,
  33559. base + (col + 1) + (row + 1) * rowLength,
  33560. base + col + (row + 1) * rowLength
  33561. ];
  33562. indices.push(square[1]);
  33563. indices.push(square[2]);
  33564. indices.push(square[3]);
  33565. indices.push(square[0]);
  33566. indices.push(square[1]);
  33567. indices.push(square[3]);
  33568. }
  33569. }
  33570. // Position, normals and uvs
  33571. var position = BABYLON.Vector3.Zero();
  33572. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33573. for (row = 0; row <= precision.h; row++) {
  33574. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  33575. for (col = 0; col <= precision.w; col++) {
  33576. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  33577. position.y = 0;
  33578. positions.push(position.x, position.y, position.z);
  33579. normals.push(normal.x, normal.y, normal.z);
  33580. uvs.push(col / precision.w, row / precision.h);
  33581. }
  33582. }
  33583. }
  33584. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33585. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33586. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33587. }
  33588. }
  33589. // Result
  33590. var vertexData = new VertexData();
  33591. vertexData.indices = indices;
  33592. vertexData.positions = positions;
  33593. vertexData.normals = normals;
  33594. vertexData.uvs = uvs;
  33595. return vertexData;
  33596. };
  33597. /**
  33598. * Creates the VertexData of the Ground designed from a heightmap.
  33599. */
  33600. VertexData.CreateGroundFromHeightMap = function (options) {
  33601. var indices = [];
  33602. var positions = [];
  33603. var normals = [];
  33604. var uvs = [];
  33605. var row, col;
  33606. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  33607. // Vertices
  33608. for (row = 0; row <= options.subdivisions; row++) {
  33609. for (col = 0; col <= options.subdivisions; col++) {
  33610. 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));
  33611. // Compute height
  33612. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33613. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33614. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33615. var r = options.buffer[pos] / 255.0;
  33616. var g = options.buffer[pos + 1] / 255.0;
  33617. var b = options.buffer[pos + 2] / 255.0;
  33618. var gradient = r * filter.r + g * filter.g + b * filter.b;
  33619. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33620. // Add vertex
  33621. positions.push(position.x, position.y, position.z);
  33622. normals.push(0, 0, 0);
  33623. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33624. }
  33625. }
  33626. // Indices
  33627. for (row = 0; row < options.subdivisions; row++) {
  33628. for (col = 0; col < options.subdivisions; col++) {
  33629. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33630. indices.push(col + 1 + row * (options.subdivisions + 1));
  33631. indices.push(col + row * (options.subdivisions + 1));
  33632. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33633. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33634. indices.push(col + row * (options.subdivisions + 1));
  33635. }
  33636. }
  33637. // Normals
  33638. VertexData.ComputeNormals(positions, indices, normals);
  33639. // Result
  33640. var vertexData = new VertexData();
  33641. vertexData.indices = indices;
  33642. vertexData.positions = positions;
  33643. vertexData.normals = normals;
  33644. vertexData.uvs = uvs;
  33645. return vertexData;
  33646. };
  33647. /**
  33648. * Creates the VertexData of the Plane.
  33649. */
  33650. VertexData.CreatePlane = function (options) {
  33651. var indices = [];
  33652. var positions = [];
  33653. var normals = [];
  33654. var uvs = [];
  33655. var width = options.width || options.size || 1;
  33656. var height = options.height || options.size || 1;
  33657. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33658. // Vertices
  33659. var halfWidth = width / 2.0;
  33660. var halfHeight = height / 2.0;
  33661. positions.push(-halfWidth, -halfHeight, 0);
  33662. normals.push(0, 0, -1.0);
  33663. uvs.push(0.0, 0.0);
  33664. positions.push(halfWidth, -halfHeight, 0);
  33665. normals.push(0, 0, -1.0);
  33666. uvs.push(1.0, 0.0);
  33667. positions.push(halfWidth, halfHeight, 0);
  33668. normals.push(0, 0, -1.0);
  33669. uvs.push(1.0, 1.0);
  33670. positions.push(-halfWidth, halfHeight, 0);
  33671. normals.push(0, 0, -1.0);
  33672. uvs.push(0.0, 1.0);
  33673. // Indices
  33674. indices.push(0);
  33675. indices.push(1);
  33676. indices.push(2);
  33677. indices.push(0);
  33678. indices.push(2);
  33679. indices.push(3);
  33680. // Sides
  33681. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33682. // Result
  33683. var vertexData = new VertexData();
  33684. vertexData.indices = indices;
  33685. vertexData.positions = positions;
  33686. vertexData.normals = normals;
  33687. vertexData.uvs = uvs;
  33688. return vertexData;
  33689. };
  33690. /**
  33691. * Creates the VertexData of the Disc or regular Polygon.
  33692. */
  33693. VertexData.CreateDisc = function (options) {
  33694. var positions = new Array();
  33695. var indices = new Array();
  33696. var normals = new Array();
  33697. var uvs = new Array();
  33698. var radius = options.radius || 0.5;
  33699. var tessellation = options.tessellation || 64;
  33700. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33701. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33702. // positions and uvs
  33703. positions.push(0, 0, 0); // disc center first
  33704. uvs.push(0.5, 0.5);
  33705. var theta = Math.PI * 2 * arc;
  33706. var step = theta / tessellation;
  33707. for (var a = 0; a < theta; a += step) {
  33708. var x = Math.cos(a);
  33709. var y = Math.sin(a);
  33710. var u = (x + 1) / 2;
  33711. var v = (1 - y) / 2;
  33712. positions.push(radius * x, radius * y, 0);
  33713. uvs.push(u, v);
  33714. }
  33715. if (arc === 1) {
  33716. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33717. uvs.push(uvs[2], uvs[3]);
  33718. }
  33719. //indices
  33720. var vertexNb = positions.length / 3;
  33721. for (var i = 1; i < vertexNb - 1; i++) {
  33722. indices.push(i + 1, 0, i);
  33723. }
  33724. // result
  33725. VertexData.ComputeNormals(positions, indices, normals);
  33726. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33727. var vertexData = new VertexData();
  33728. vertexData.indices = indices;
  33729. vertexData.positions = positions;
  33730. vertexData.normals = normals;
  33731. vertexData.uvs = uvs;
  33732. return vertexData;
  33733. };
  33734. /**
  33735. * Re-creates the VertexData of the Polygon for sideOrientation.
  33736. */
  33737. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  33738. var faceUV = fUV || new Array(3);
  33739. var faceColors = fColors;
  33740. var colors = [];
  33741. // default face colors and UV if undefined
  33742. for (var f = 0; f < 3; f++) {
  33743. if (faceUV[f] === undefined) {
  33744. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33745. }
  33746. if (faceColors && faceColors[f] === undefined) {
  33747. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33748. }
  33749. }
  33750. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33751. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33752. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33753. var indices = polygon.getIndices();
  33754. // set face colours and textures
  33755. var idx = 0;
  33756. var face = 0;
  33757. for (var index = 0; index < normals.length; index += 3) {
  33758. //Edge Face no. 1
  33759. if (Math.abs(normals[index + 1]) < 0.001) {
  33760. face = 1;
  33761. }
  33762. //Top Face no. 0
  33763. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  33764. face = 0;
  33765. }
  33766. //Bottom Face no. 2
  33767. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  33768. face = 2;
  33769. }
  33770. idx = index / 3;
  33771. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  33772. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  33773. if (faceColors) {
  33774. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  33775. }
  33776. }
  33777. // sides
  33778. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  33779. // Result
  33780. var vertexData = new VertexData();
  33781. vertexData.indices = indices;
  33782. vertexData.positions = positions;
  33783. vertexData.normals = normals;
  33784. vertexData.uvs = uvs;
  33785. if (faceColors) {
  33786. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33787. vertexData.colors = totalColors;
  33788. }
  33789. return vertexData;
  33790. };
  33791. /**
  33792. * Creates the VertexData of the IcoSphere.
  33793. */
  33794. VertexData.CreateIcoSphere = function (options) {
  33795. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33796. var radius = options.radius || 1;
  33797. var flat = (options.flat === undefined) ? true : options.flat;
  33798. var subdivisions = options.subdivisions || 4;
  33799. var radiusX = options.radiusX || radius;
  33800. var radiusY = options.radiusY || radius;
  33801. var radiusZ = options.radiusZ || radius;
  33802. var t = (1 + Math.sqrt(5)) / 2;
  33803. // 12 vertex x,y,z
  33804. var ico_vertices = [
  33805. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33806. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33807. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33808. ];
  33809. // index of 3 vertex makes a face of icopshere
  33810. var ico_indices = [
  33811. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33812. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33813. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33814. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33815. ];
  33816. // vertex for uv have aliased position, not for UV
  33817. var vertices_unalias_id = [
  33818. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33819. // vertex alias
  33820. 0,
  33821. 2,
  33822. 3,
  33823. 3,
  33824. 3,
  33825. 4,
  33826. 7,
  33827. 8,
  33828. 9,
  33829. 9,
  33830. 10,
  33831. 11 // 23: B + 12
  33832. ];
  33833. // uv as integer step (not pixels !)
  33834. var ico_vertexuv = [
  33835. 5, 1, 3, 1, 6, 4, 0, 0,
  33836. 5, 3, 4, 2, 2, 2, 4, 0,
  33837. 2, 0, 1, 1, 6, 0, 6, 2,
  33838. // vertex alias (for same vertex on different faces)
  33839. 0, 4,
  33840. 3, 3,
  33841. 4, 4,
  33842. 3, 1,
  33843. 4, 2,
  33844. 4, 4,
  33845. 0, 2,
  33846. 1, 1,
  33847. 2, 2,
  33848. 3, 3,
  33849. 1, 3,
  33850. 2, 4 // 23: B + 12
  33851. ];
  33852. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33853. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33854. // First island of uv mapping
  33855. // v = 4h 3+ 2
  33856. // v = 3h 9+ 4
  33857. // v = 2h 9+ 5 B
  33858. // v = 1h 9 1 0
  33859. // v = 0h 3 8 7 A
  33860. // u = 0 1 2 3 4 5 6 *a
  33861. // Second island of uv mapping
  33862. // v = 4h 0+ B+ 4+
  33863. // v = 3h A+ 2+
  33864. // v = 2h 7+ 6 3+
  33865. // v = 1h 8+ 3+
  33866. // v = 0h
  33867. // u = 0 1 2 3 4 5 6 *a
  33868. // Face layout on texture UV mapping
  33869. // ============
  33870. // \ 4 /\ 16 / ======
  33871. // \ / \ / /\ 11 /
  33872. // \/ 7 \/ / \ /
  33873. // ======= / 10 \/
  33874. // /\ 17 /\ =======
  33875. // / \ / \ \ 15 /\
  33876. // / 8 \/ 12 \ \ / \
  33877. // ============ \/ 6 \
  33878. // \ 18 /\ ============
  33879. // \ / \ \ 5 /\ 0 /
  33880. // \/ 13 \ \ / \ /
  33881. // ======= \/ 1 \/
  33882. // =============
  33883. // /\ 19 /\ 2 /\
  33884. // / \ / \ / \
  33885. // / 14 \/ 9 \/ 3 \
  33886. // ===================
  33887. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  33888. var ustep = 138 / 1024;
  33889. var vstep = 239 / 1024;
  33890. var uoffset = 60 / 1024;
  33891. var voffset = 26 / 1024;
  33892. // Second island should have margin, not to touch the first island
  33893. // avoid any borderline artefact in pixel rounding
  33894. var island_u_offset = -40 / 1024;
  33895. var island_v_offset = +20 / 1024;
  33896. // face is either island 0 or 1 :
  33897. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  33898. var island = [
  33899. 0, 0, 0, 0, 1,
  33900. 0, 0, 1, 1, 0,
  33901. 0, 0, 1, 1, 0,
  33902. 0, 1, 1, 1, 0 // 15 - 19
  33903. ];
  33904. var indices = new Array();
  33905. var positions = new Array();
  33906. var normals = new Array();
  33907. var uvs = new Array();
  33908. var current_indice = 0;
  33909. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  33910. var face_vertex_pos = new Array(3);
  33911. var face_vertex_uv = new Array(3);
  33912. var v012;
  33913. for (v012 = 0; v012 < 3; v012++) {
  33914. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  33915. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  33916. }
  33917. // create all with normals
  33918. for (var face = 0; face < 20; face++) {
  33919. // 3 vertex per face
  33920. for (v012 = 0; v012 < 3; v012++) {
  33921. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  33922. var v_id = ico_indices[3 * face + v012];
  33923. // vertex have 3D position (x,y,z)
  33924. 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]);
  33925. // Normalize to get normal, then scale to radius
  33926. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  33927. // uv Coordinates from vertex ID
  33928. 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);
  33929. }
  33930. // Subdivide the face (interpolate pos, norm, uv)
  33931. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  33932. // - norm is linear interpolation of vertex corner normal
  33933. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  33934. // - uv is linear interpolation
  33935. //
  33936. // Topology is as below for sub-divide by 2
  33937. // vertex shown as v0,v1,v2
  33938. // interp index is i1 to progress in range [v0,v1[
  33939. // interp index is i2 to progress in range [v0,v2[
  33940. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  33941. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33942. //
  33943. //
  33944. // i2 v2
  33945. // ^ ^
  33946. // / / \
  33947. // / / \
  33948. // / / \
  33949. // / / (0,1) \
  33950. // / #---------\
  33951. // / / \ (0,0)'/ \
  33952. // / / \ / \
  33953. // / / \ / \
  33954. // / / (0,0) \ / (1,0) \
  33955. // / #---------#---------\
  33956. // v0 v1
  33957. //
  33958. // --------------------> i1
  33959. //
  33960. // interp of (i1,i2):
  33961. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  33962. // along i1 : lerp(x0,x1, i1/(S-i2))
  33963. //
  33964. // centroid of triangle is needed to get help normal computation
  33965. // (c1,c2) are used for centroid location
  33966. var interp_vertex = function (i1, i2, c1, c2) {
  33967. // vertex is interpolated from
  33968. // - face_vertex_pos[0..2]
  33969. // - face_vertex_uv[0..2]
  33970. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  33971. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  33972. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  33973. pos_interp.normalize();
  33974. var vertex_normal;
  33975. if (flat) {
  33976. // in flat mode, recalculate normal as face centroid normal
  33977. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  33978. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  33979. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  33980. }
  33981. else {
  33982. // in smooth mode, recalculate normal from each single vertex position
  33983. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  33984. }
  33985. // Vertex normal need correction due to X,Y,Z radius scaling
  33986. vertex_normal.x /= radiusX;
  33987. vertex_normal.y /= radiusY;
  33988. vertex_normal.z /= radiusZ;
  33989. vertex_normal.normalize();
  33990. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  33991. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  33992. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  33993. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  33994. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  33995. uvs.push(uv_interp.x, uv_interp.y);
  33996. // push each vertex has member of a face
  33997. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  33998. indices.push(current_indice);
  33999. current_indice++;
  34000. };
  34001. for (var i2 = 0; i2 < subdivisions; i2++) {
  34002. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  34003. // face : (i1,i2) for /\ :
  34004. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  34005. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34006. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34007. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34008. if (i1 + i2 + 1 < subdivisions) {
  34009. // face : (i1,i2)' for \/ :
  34010. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34011. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34012. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34013. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34014. }
  34015. }
  34016. }
  34017. }
  34018. // Sides
  34019. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34020. // Result
  34021. var vertexData = new VertexData();
  34022. vertexData.indices = indices;
  34023. vertexData.positions = positions;
  34024. vertexData.normals = normals;
  34025. vertexData.uvs = uvs;
  34026. return vertexData;
  34027. };
  34028. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  34029. /**
  34030. * Creates the VertexData of the Polyhedron.
  34031. */
  34032. VertexData.CreatePolyhedron = function (options) {
  34033. // provided polyhedron types :
  34034. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  34035. // 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)
  34036. var polyhedra = [];
  34037. 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]] };
  34038. 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]] };
  34039. polyhedra[2] = {
  34040. 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]],
  34041. 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]]
  34042. };
  34043. polyhedra[3] = {
  34044. 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]],
  34045. 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]]
  34046. };
  34047. polyhedra[4] = {
  34048. 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]],
  34049. 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]]
  34050. };
  34051. 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]] };
  34052. 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]] };
  34053. 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]] };
  34054. 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]] };
  34055. 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]] };
  34056. 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]] };
  34057. 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]] };
  34058. 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]] };
  34059. 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]] };
  34060. polyhedra[14] = {
  34061. 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]],
  34062. 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]]
  34063. };
  34064. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34065. var size = options.size;
  34066. var sizeX = options.sizeX || size || 1;
  34067. var sizeY = options.sizeY || size || 1;
  34068. var sizeZ = options.sizeZ || size || 1;
  34069. var data = options.custom || polyhedra[type];
  34070. var nbfaces = data.face.length;
  34071. var faceUV = options.faceUV || new Array(nbfaces);
  34072. var faceColors = options.faceColors;
  34073. var flat = (options.flat === undefined) ? true : options.flat;
  34074. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34075. var positions = new Array();
  34076. var indices = new Array();
  34077. var normals = new Array();
  34078. var uvs = new Array();
  34079. var colors = new Array();
  34080. var index = 0;
  34081. var faceIdx = 0; // face cursor in the array "indexes"
  34082. var indexes = new Array();
  34083. var i = 0;
  34084. var f = 0;
  34085. var u, v, ang, x, y, tmp;
  34086. // default face colors and UV if undefined
  34087. if (flat) {
  34088. for (f = 0; f < nbfaces; f++) {
  34089. if (faceColors && faceColors[f] === undefined) {
  34090. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34091. }
  34092. if (faceUV && faceUV[f] === undefined) {
  34093. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34094. }
  34095. }
  34096. }
  34097. if (!flat) {
  34098. for (i = 0; i < data.vertex.length; i++) {
  34099. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34100. uvs.push(0, 0);
  34101. }
  34102. for (f = 0; f < nbfaces; f++) {
  34103. for (i = 0; i < data.face[f].length - 2; i++) {
  34104. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34105. }
  34106. }
  34107. }
  34108. else {
  34109. for (f = 0; f < nbfaces; f++) {
  34110. var fl = data.face[f].length; // number of vertices of the current face
  34111. ang = 2 * Math.PI / fl;
  34112. x = 0.5 * Math.tan(ang / 2);
  34113. y = 0.5;
  34114. // positions, uvs, colors
  34115. for (i = 0; i < fl; i++) {
  34116. // positions
  34117. 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);
  34118. indexes.push(index);
  34119. index++;
  34120. // uvs
  34121. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34122. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34123. uvs.push(u, v);
  34124. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34125. y = x * Math.sin(ang) + y * Math.cos(ang);
  34126. x = tmp;
  34127. // colors
  34128. if (faceColors) {
  34129. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34130. }
  34131. }
  34132. // indices from indexes
  34133. for (i = 0; i < fl - 2; i++) {
  34134. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34135. }
  34136. faceIdx += fl;
  34137. }
  34138. }
  34139. VertexData.ComputeNormals(positions, indices, normals);
  34140. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34141. var vertexData = new VertexData();
  34142. vertexData.positions = positions;
  34143. vertexData.indices = indices;
  34144. vertexData.normals = normals;
  34145. vertexData.uvs = uvs;
  34146. if (faceColors && flat) {
  34147. vertexData.colors = colors;
  34148. }
  34149. return vertexData;
  34150. };
  34151. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34152. /**
  34153. * Creates the VertexData of the Torus Knot.
  34154. */
  34155. VertexData.CreateTorusKnot = function (options) {
  34156. var indices = new Array();
  34157. var positions = new Array();
  34158. var normals = new Array();
  34159. var uvs = new Array();
  34160. var radius = options.radius || 2;
  34161. var tube = options.tube || 0.5;
  34162. var radialSegments = options.radialSegments || 32;
  34163. var tubularSegments = options.tubularSegments || 32;
  34164. var p = options.p || 2;
  34165. var q = options.q || 3;
  34166. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34167. // Helper
  34168. var getPos = function (angle) {
  34169. var cu = Math.cos(angle);
  34170. var su = Math.sin(angle);
  34171. var quOverP = q / p * angle;
  34172. var cs = Math.cos(quOverP);
  34173. var tx = radius * (2 + cs) * 0.5 * cu;
  34174. var ty = radius * (2 + cs) * su * 0.5;
  34175. var tz = radius * Math.sin(quOverP) * 0.5;
  34176. return new BABYLON.Vector3(tx, ty, tz);
  34177. };
  34178. // Vertices
  34179. var i;
  34180. var j;
  34181. for (i = 0; i <= radialSegments; i++) {
  34182. var modI = i % radialSegments;
  34183. var u = modI / radialSegments * 2 * p * Math.PI;
  34184. var p1 = getPos(u);
  34185. var p2 = getPos(u + 0.01);
  34186. var tang = p2.subtract(p1);
  34187. var n = p2.add(p1);
  34188. var bitan = BABYLON.Vector3.Cross(tang, n);
  34189. n = BABYLON.Vector3.Cross(bitan, tang);
  34190. bitan.normalize();
  34191. n.normalize();
  34192. for (j = 0; j < tubularSegments; j++) {
  34193. var modJ = j % tubularSegments;
  34194. var v = modJ / tubularSegments * 2 * Math.PI;
  34195. var cx = -tube * Math.cos(v);
  34196. var cy = tube * Math.sin(v);
  34197. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34198. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34199. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34200. uvs.push(i / radialSegments);
  34201. uvs.push(j / tubularSegments);
  34202. }
  34203. }
  34204. for (i = 0; i < radialSegments; i++) {
  34205. for (j = 0; j < tubularSegments; j++) {
  34206. var jNext = (j + 1) % tubularSegments;
  34207. var a = i * tubularSegments + j;
  34208. var b = (i + 1) * tubularSegments + j;
  34209. var c = (i + 1) * tubularSegments + jNext;
  34210. var d = i * tubularSegments + jNext;
  34211. indices.push(d);
  34212. indices.push(b);
  34213. indices.push(a);
  34214. indices.push(d);
  34215. indices.push(c);
  34216. indices.push(b);
  34217. }
  34218. }
  34219. // Normals
  34220. VertexData.ComputeNormals(positions, indices, normals);
  34221. // Sides
  34222. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34223. // Result
  34224. var vertexData = new VertexData();
  34225. vertexData.indices = indices;
  34226. vertexData.positions = positions;
  34227. vertexData.normals = normals;
  34228. vertexData.uvs = uvs;
  34229. return vertexData;
  34230. };
  34231. // Tools
  34232. /**
  34233. * @param {any} - positions (number[] or Float32Array)
  34234. * @param {any} - indices (number[] or Uint16Array)
  34235. * @param {any} - normals (number[] or Float32Array)
  34236. * options (optional) :
  34237. * facetPositions : optional array of facet positions (vector3)
  34238. * facetNormals : optional array of facet normals (vector3)
  34239. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34240. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34241. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34242. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34243. * bInfo : optional bounding info, required for facetPartitioning computation
  34244. * useRightHandedSystem: optional boolean to for right handed system computation
  34245. * depthSort : optional boolean to enable the facet depth sort computation
  34246. * distanceTo : optional Vector3 to compute the facet depth from this location
  34247. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34248. */
  34249. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34250. // temporary scalar variables
  34251. var index = 0; // facet index
  34252. var p1p2x = 0.0; // p1p2 vector x coordinate
  34253. var p1p2y = 0.0; // p1p2 vector y coordinate
  34254. var p1p2z = 0.0; // p1p2 vector z coordinate
  34255. var p3p2x = 0.0; // p3p2 vector x coordinate
  34256. var p3p2y = 0.0; // p3p2 vector y coordinate
  34257. var p3p2z = 0.0; // p3p2 vector z coordinate
  34258. var faceNormalx = 0.0; // facet normal x coordinate
  34259. var faceNormaly = 0.0; // facet normal y coordinate
  34260. var faceNormalz = 0.0; // facet normal z coordinate
  34261. var length = 0.0; // facet normal length before normalization
  34262. var v1x = 0; // vector1 x index in the positions array
  34263. var v1y = 0; // vector1 y index in the positions array
  34264. var v1z = 0; // vector1 z index in the positions array
  34265. var v2x = 0; // vector2 x index in the positions array
  34266. var v2y = 0; // vector2 y index in the positions array
  34267. var v2z = 0; // vector2 z index in the positions array
  34268. var v3x = 0; // vector3 x index in the positions array
  34269. var v3y = 0; // vector3 y index in the positions array
  34270. var v3z = 0; // vector3 z index in the positions array
  34271. var computeFacetNormals = false;
  34272. var computeFacetPositions = false;
  34273. var computeFacetPartitioning = false;
  34274. var computeDepthSort = false;
  34275. var faceNormalSign = 1;
  34276. var ratio = 0;
  34277. var distanceTo = null;
  34278. if (options) {
  34279. computeFacetNormals = (options.facetNormals) ? true : false;
  34280. computeFacetPositions = (options.facetPositions) ? true : false;
  34281. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34282. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34283. ratio = options.ratio || 0;
  34284. computeDepthSort = (options.depthSort) ? true : false;
  34285. distanceTo = (options.distanceTo);
  34286. if (computeDepthSort) {
  34287. if (distanceTo === undefined) {
  34288. distanceTo = BABYLON.Vector3.Zero();
  34289. }
  34290. var depthSortedFacets = options.depthSortedFacets;
  34291. }
  34292. }
  34293. // facetPartitioning reinit if needed
  34294. var xSubRatio = 0;
  34295. var ySubRatio = 0;
  34296. var zSubRatio = 0;
  34297. var subSq = 0;
  34298. if (computeFacetPartitioning && options && options.bbSize) {
  34299. var ox = 0; // X partitioning index for facet position
  34300. var oy = 0; // Y partinioning index for facet position
  34301. var oz = 0; // Z partinioning index for facet position
  34302. var b1x = 0; // X partitioning index for facet v1 vertex
  34303. var b1y = 0; // Y partitioning index for facet v1 vertex
  34304. var b1z = 0; // z partitioning index for facet v1 vertex
  34305. var b2x = 0; // X partitioning index for facet v2 vertex
  34306. var b2y = 0; // Y partitioning index for facet v2 vertex
  34307. var b2z = 0; // Z partitioning index for facet v2 vertex
  34308. var b3x = 0; // X partitioning index for facet v3 vertex
  34309. var b3y = 0; // Y partitioning index for facet v3 vertex
  34310. var b3z = 0; // Z partitioning index for facet v3 vertex
  34311. var block_idx_o = 0; // facet barycenter block index
  34312. var block_idx_v1 = 0; // v1 vertex block index
  34313. var block_idx_v2 = 0; // v2 vertex block index
  34314. var block_idx_v3 = 0; // v3 vertex block index
  34315. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34316. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34317. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  34318. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  34319. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  34320. subSq = options.subDiv.max * options.subDiv.max;
  34321. options.facetPartitioning.length = 0;
  34322. }
  34323. // reset the normals
  34324. for (index = 0; index < positions.length; index++) {
  34325. normals[index] = 0.0;
  34326. }
  34327. // Loop : 1 indice triplet = 1 facet
  34328. var nbFaces = (indices.length / 3) | 0;
  34329. for (index = 0; index < nbFaces; index++) {
  34330. // get the indexes of the coordinates of each vertex of the facet
  34331. v1x = indices[index * 3] * 3;
  34332. v1y = v1x + 1;
  34333. v1z = v1x + 2;
  34334. v2x = indices[index * 3 + 1] * 3;
  34335. v2y = v2x + 1;
  34336. v2z = v2x + 2;
  34337. v3x = indices[index * 3 + 2] * 3;
  34338. v3y = v3x + 1;
  34339. v3z = v3x + 2;
  34340. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34341. p1p2y = positions[v1y] - positions[v2y];
  34342. p1p2z = positions[v1z] - positions[v2z];
  34343. p3p2x = positions[v3x] - positions[v2x];
  34344. p3p2y = positions[v3y] - positions[v2y];
  34345. p3p2z = positions[v3z] - positions[v2z];
  34346. // compute the face normal with the cross product
  34347. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  34348. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  34349. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  34350. // normalize this normal and store it in the array facetData
  34351. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34352. length = (length === 0) ? 1.0 : length;
  34353. faceNormalx /= length;
  34354. faceNormaly /= length;
  34355. faceNormalz /= length;
  34356. if (computeFacetNormals && options) {
  34357. options.facetNormals[index].x = faceNormalx;
  34358. options.facetNormals[index].y = faceNormaly;
  34359. options.facetNormals[index].z = faceNormalz;
  34360. }
  34361. if (computeFacetPositions && options) {
  34362. // compute and the facet barycenter coordinates in the array facetPositions
  34363. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34364. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34365. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34366. }
  34367. if (computeFacetPartitioning && options) {
  34368. // store the facet indexes in arrays in the main facetPartitioning array :
  34369. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34370. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  34371. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  34372. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  34373. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34374. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34375. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34376. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34377. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34378. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34379. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34380. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34381. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34382. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  34383. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  34384. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  34385. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  34386. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  34387. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  34388. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  34389. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34390. // push each facet index in each block containing the vertex
  34391. options.facetPartitioning[block_idx_v1].push(index);
  34392. if (block_idx_v2 != block_idx_v1) {
  34393. options.facetPartitioning[block_idx_v2].push(index);
  34394. }
  34395. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34396. options.facetPartitioning[block_idx_v3].push(index);
  34397. }
  34398. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34399. options.facetPartitioning[block_idx_o].push(index);
  34400. }
  34401. }
  34402. if (computeDepthSort && options && options.facetPositions) {
  34403. var dsf = depthSortedFacets[index];
  34404. dsf.ind = index * 3;
  34405. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  34406. }
  34407. // compute the normals anyway
  34408. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34409. normals[v1y] += faceNormaly;
  34410. normals[v1z] += faceNormalz;
  34411. normals[v2x] += faceNormalx;
  34412. normals[v2y] += faceNormaly;
  34413. normals[v2z] += faceNormalz;
  34414. normals[v3x] += faceNormalx;
  34415. normals[v3y] += faceNormaly;
  34416. normals[v3z] += faceNormalz;
  34417. }
  34418. // last normalization of each normal
  34419. for (index = 0; index < normals.length / 3; index++) {
  34420. faceNormalx = normals[index * 3];
  34421. faceNormaly = normals[index * 3 + 1];
  34422. faceNormalz = normals[index * 3 + 2];
  34423. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34424. length = (length === 0) ? 1.0 : length;
  34425. faceNormalx /= length;
  34426. faceNormaly /= length;
  34427. faceNormalz /= length;
  34428. normals[index * 3] = faceNormalx;
  34429. normals[index * 3 + 1] = faceNormaly;
  34430. normals[index * 3 + 2] = faceNormalz;
  34431. }
  34432. };
  34433. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  34434. var li = indices.length;
  34435. var ln = normals.length;
  34436. var i;
  34437. var n;
  34438. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34439. switch (sideOrientation) {
  34440. case BABYLON.Mesh.FRONTSIDE:
  34441. // nothing changed
  34442. break;
  34443. case BABYLON.Mesh.BACKSIDE:
  34444. var tmp;
  34445. // indices
  34446. for (i = 0; i < li; i += 3) {
  34447. tmp = indices[i];
  34448. indices[i] = indices[i + 2];
  34449. indices[i + 2] = tmp;
  34450. }
  34451. // normals
  34452. for (n = 0; n < ln; n++) {
  34453. normals[n] = -normals[n];
  34454. }
  34455. break;
  34456. case BABYLON.Mesh.DOUBLESIDE:
  34457. // positions
  34458. var lp = positions.length;
  34459. var l = lp / 3;
  34460. for (var p = 0; p < lp; p++) {
  34461. positions[lp + p] = positions[p];
  34462. }
  34463. // indices
  34464. for (i = 0; i < li; i += 3) {
  34465. indices[i + li] = indices[i + 2] + l;
  34466. indices[i + 1 + li] = indices[i + 1] + l;
  34467. indices[i + 2 + li] = indices[i] + l;
  34468. }
  34469. // normals
  34470. for (n = 0; n < ln; n++) {
  34471. normals[ln + n] = -normals[n];
  34472. }
  34473. // uvs
  34474. var lu = uvs.length;
  34475. var u = 0;
  34476. for (u = 0; u < lu; u++) {
  34477. uvs[u + lu] = uvs[u];
  34478. }
  34479. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34480. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34481. u = 0;
  34482. for (i = 0; i < lu / 2; i++) {
  34483. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  34484. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  34485. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  34486. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  34487. u += 2;
  34488. }
  34489. break;
  34490. }
  34491. };
  34492. /**
  34493. * Creates a new VertexData from the imported parameters.
  34494. */
  34495. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  34496. var vertexData = new VertexData();
  34497. // positions
  34498. var positions = parsedVertexData.positions;
  34499. if (positions) {
  34500. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  34501. }
  34502. // normals
  34503. var normals = parsedVertexData.normals;
  34504. if (normals) {
  34505. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  34506. }
  34507. // tangents
  34508. var tangents = parsedVertexData.tangents;
  34509. if (tangents) {
  34510. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  34511. }
  34512. // uvs
  34513. var uvs = parsedVertexData.uvs;
  34514. if (uvs) {
  34515. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  34516. }
  34517. // uv2s
  34518. var uv2s = parsedVertexData.uv2s;
  34519. if (uv2s) {
  34520. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  34521. }
  34522. // uv3s
  34523. var uv3s = parsedVertexData.uv3s;
  34524. if (uv3s) {
  34525. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  34526. }
  34527. // uv4s
  34528. var uv4s = parsedVertexData.uv4s;
  34529. if (uv4s) {
  34530. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  34531. }
  34532. // uv5s
  34533. var uv5s = parsedVertexData.uv5s;
  34534. if (uv5s) {
  34535. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  34536. }
  34537. // uv6s
  34538. var uv6s = parsedVertexData.uv6s;
  34539. if (uv6s) {
  34540. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  34541. }
  34542. // colors
  34543. var colors = parsedVertexData.colors;
  34544. if (colors) {
  34545. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  34546. }
  34547. // matricesIndices
  34548. var matricesIndices = parsedVertexData.matricesIndices;
  34549. if (matricesIndices) {
  34550. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  34551. }
  34552. // matricesWeights
  34553. var matricesWeights = parsedVertexData.matricesWeights;
  34554. if (matricesWeights) {
  34555. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  34556. }
  34557. // indices
  34558. var indices = parsedVertexData.indices;
  34559. if (indices) {
  34560. vertexData.indices = indices;
  34561. }
  34562. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  34563. };
  34564. return VertexData;
  34565. }());
  34566. BABYLON.VertexData = VertexData;
  34567. })(BABYLON || (BABYLON = {}));
  34568. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  34569. var BABYLON;
  34570. (function (BABYLON) {
  34571. /**
  34572. * Class used to store geometry data (vertex buffers + index buffer)
  34573. */
  34574. var Geometry = /** @class */ (function () {
  34575. /**
  34576. * Creates a new geometry
  34577. * @param id defines the unique ID
  34578. * @param scene defines the hosting scene
  34579. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  34580. * @param updatable defines if geometry must be updatable (false by default)
  34581. * @param mesh defines the mesh that will be associated with the geometry
  34582. */
  34583. function Geometry(id, scene, vertexData, updatable, mesh) {
  34584. if (updatable === void 0) { updatable = false; }
  34585. if (mesh === void 0) { mesh = null; }
  34586. /**
  34587. * Gets the delay loading state of the geometry (none by default which means not delayed)
  34588. */
  34589. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34590. this._totalVertices = 0;
  34591. this._isDisposed = false;
  34592. this._indexBufferIsUpdatable = false;
  34593. this.id = id;
  34594. this._engine = scene.getEngine();
  34595. this._meshes = [];
  34596. this._scene = scene;
  34597. //Init vertex buffer cache
  34598. this._vertexBuffers = {};
  34599. this._indices = [];
  34600. this._updatable = updatable;
  34601. // vertexData
  34602. if (vertexData) {
  34603. this.setAllVerticesData(vertexData, updatable);
  34604. }
  34605. else {
  34606. this._totalVertices = 0;
  34607. this._indices = [];
  34608. }
  34609. if (this._engine.getCaps().vertexArrayObject) {
  34610. this._vertexArrayObjects = {};
  34611. }
  34612. // applyToMesh
  34613. if (mesh) {
  34614. if (mesh.getClassName() === "LinesMesh") {
  34615. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34616. this.updateExtend();
  34617. }
  34618. this.applyToMesh(mesh);
  34619. mesh.computeWorldMatrix(true);
  34620. }
  34621. }
  34622. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34623. /**
  34624. * 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
  34625. */
  34626. get: function () {
  34627. return this._boundingBias;
  34628. },
  34629. /**
  34630. * 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
  34631. */
  34632. set: function (value) {
  34633. if (this._boundingBias && this._boundingBias.equals(value)) {
  34634. return;
  34635. }
  34636. this._boundingBias = value.clone();
  34637. this.updateBoundingInfo(true, null);
  34638. },
  34639. enumerable: true,
  34640. configurable: true
  34641. });
  34642. /**
  34643. * Static function used to attach a new empty geometry to a mesh
  34644. * @param mesh defines the mesh to attach the geometry to
  34645. * @returns the new {BABYLON.Geometry}
  34646. */
  34647. Geometry.CreateGeometryForMesh = function (mesh) {
  34648. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  34649. geometry.applyToMesh(mesh);
  34650. return geometry;
  34651. };
  34652. Object.defineProperty(Geometry.prototype, "extend", {
  34653. /**
  34654. * Gets the current extend of the geometry
  34655. */
  34656. get: function () {
  34657. return this._extend;
  34658. },
  34659. enumerable: true,
  34660. configurable: true
  34661. });
  34662. /**
  34663. * Gets the hosting scene
  34664. * @returns the hosting {BABYLON.Scene}
  34665. */
  34666. Geometry.prototype.getScene = function () {
  34667. return this._scene;
  34668. };
  34669. /**
  34670. * Gets the hosting engine
  34671. * @returns the hosting {BABYLON.Engine}
  34672. */
  34673. Geometry.prototype.getEngine = function () {
  34674. return this._engine;
  34675. };
  34676. /**
  34677. * Defines if the geometry is ready to use
  34678. * @returns true if the geometry is ready to be used
  34679. */
  34680. Geometry.prototype.isReady = function () {
  34681. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34682. };
  34683. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  34684. /**
  34685. * Gets a value indicating that the geometry should not be serialized
  34686. */
  34687. get: function () {
  34688. for (var index = 0; index < this._meshes.length; index++) {
  34689. if (!this._meshes[index].doNotSerialize) {
  34690. return false;
  34691. }
  34692. }
  34693. return true;
  34694. },
  34695. enumerable: true,
  34696. configurable: true
  34697. });
  34698. /** @ignore */
  34699. Geometry.prototype._rebuild = function () {
  34700. if (this._vertexArrayObjects) {
  34701. this._vertexArrayObjects = {};
  34702. }
  34703. // Index buffer
  34704. if (this._meshes.length !== 0 && this._indices) {
  34705. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34706. }
  34707. // Vertex buffers
  34708. for (var key in this._vertexBuffers) {
  34709. var vertexBuffer = this._vertexBuffers[key];
  34710. vertexBuffer._rebuild();
  34711. }
  34712. };
  34713. /**
  34714. * Affects all gemetry data in one call
  34715. * @param vertexData defines the geometry data
  34716. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  34717. */
  34718. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34719. vertexData.applyToGeometry(this, updatable);
  34720. this.notifyUpdate();
  34721. };
  34722. /**
  34723. * Set specific vertex data
  34724. * @param kind defines the data kind (Position, normal, etc...)
  34725. * @param data defines the vertex data to use
  34726. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  34727. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  34728. */
  34729. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34730. if (updatable === void 0) { updatable = false; }
  34731. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34732. this.setVerticesBuffer(buffer);
  34733. };
  34734. /**
  34735. * Removes a specific vertex data
  34736. * @param kind defines the data kind (Position, normal, etc...)
  34737. */
  34738. Geometry.prototype.removeVerticesData = function (kind) {
  34739. if (this._vertexBuffers[kind]) {
  34740. this._vertexBuffers[kind].dispose();
  34741. delete this._vertexBuffers[kind];
  34742. }
  34743. };
  34744. /**
  34745. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  34746. * @param buffer defines the vertex buffer to use
  34747. */
  34748. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34749. var kind = buffer.getKind();
  34750. if (this._vertexBuffers[kind]) {
  34751. this._vertexBuffers[kind].dispose();
  34752. }
  34753. this._vertexBuffers[kind] = buffer;
  34754. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34755. var data = buffer.getData();
  34756. var stride = buffer.getStrideSize();
  34757. this._totalVertices = data.length / stride;
  34758. this.updateExtend(data, stride);
  34759. this._resetPointsArrayCache();
  34760. var meshes = this._meshes;
  34761. var numOfMeshes = meshes.length;
  34762. for (var index = 0; index < numOfMeshes; index++) {
  34763. var mesh = meshes[index];
  34764. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34765. mesh._createGlobalSubMesh(false);
  34766. mesh.computeWorldMatrix(true);
  34767. }
  34768. }
  34769. this.notifyUpdate(kind);
  34770. if (this._vertexArrayObjects) {
  34771. this._disposeVertexArrayObjects();
  34772. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  34773. }
  34774. };
  34775. /**
  34776. * Update a specific vertex buffer
  34777. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  34778. * It will do nothing if the buffer is not updatable
  34779. * @param kind defines the data kind (Position, normal, etc...)
  34780. * @param data defines the data to use
  34781. * @param offset defines the offset in the target buffer where to store the data
  34782. */
  34783. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34784. var vertexBuffer = this.getVertexBuffer(kind);
  34785. if (!vertexBuffer) {
  34786. return;
  34787. }
  34788. vertexBuffer.updateDirectly(data, offset);
  34789. this.notifyUpdate(kind);
  34790. };
  34791. /**
  34792. * Update a specific vertex buffer
  34793. * This function will create a new buffer if the current one is not updatable
  34794. * @param kind defines the data kind (Position, normal, etc...)
  34795. * @param data defines the data to use
  34796. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  34797. */
  34798. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  34799. if (updateExtends === void 0) { updateExtends = false; }
  34800. var vertexBuffer = this.getVertexBuffer(kind);
  34801. if (!vertexBuffer) {
  34802. return;
  34803. }
  34804. vertexBuffer.update(data);
  34805. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34806. var stride = vertexBuffer.getStrideSize();
  34807. this._totalVertices = data.length / stride;
  34808. this.updateBoundingInfo(updateExtends, data);
  34809. }
  34810. this.notifyUpdate(kind);
  34811. };
  34812. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  34813. if (updateExtends) {
  34814. this.updateExtend(data);
  34815. }
  34816. var meshes = this._meshes;
  34817. var numOfMeshes = meshes.length;
  34818. this._resetPointsArrayCache();
  34819. for (var index = 0; index < numOfMeshes; index++) {
  34820. var mesh = meshes[index];
  34821. if (updateExtends) {
  34822. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34823. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34824. var subMesh = mesh.subMeshes[subIndex];
  34825. subMesh.refreshBoundingInfo();
  34826. }
  34827. }
  34828. }
  34829. };
  34830. /** @ignore */
  34831. Geometry.prototype._bind = function (effect, indexToBind) {
  34832. if (!effect) {
  34833. return;
  34834. }
  34835. if (indexToBind === undefined) {
  34836. indexToBind = this._indexBuffer;
  34837. }
  34838. var vbs = this.getVertexBuffers();
  34839. if (!vbs) {
  34840. return;
  34841. }
  34842. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  34843. this._engine.bindBuffers(vbs, indexToBind, effect);
  34844. return;
  34845. }
  34846. // Using VAO
  34847. if (!this._vertexArrayObjects[effect.key]) {
  34848. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  34849. }
  34850. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  34851. };
  34852. /**
  34853. * Gets total number of vertices
  34854. * @returns the total number of vertices
  34855. */
  34856. Geometry.prototype.getTotalVertices = function () {
  34857. if (!this.isReady()) {
  34858. return 0;
  34859. }
  34860. return this._totalVertices;
  34861. };
  34862. /**
  34863. * Gets a specific vertex data attached to this geometry
  34864. * @param kind defines the data kind (Position, normal, etc...)
  34865. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34866. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  34867. * @returns a float array containing vertex data
  34868. */
  34869. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  34870. var vertexBuffer = this.getVertexBuffer(kind);
  34871. if (!vertexBuffer) {
  34872. return null;
  34873. }
  34874. var orig = vertexBuffer.getData();
  34875. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  34876. return orig;
  34877. }
  34878. else {
  34879. var len = orig.length;
  34880. var copy = [];
  34881. for (var i = 0; i < len; i++) {
  34882. copy.push(orig[i]);
  34883. }
  34884. return copy;
  34885. }
  34886. };
  34887. /**
  34888. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  34889. * @param kind defines the data kind (Position, normal, etc...)
  34890. * @returns true if the vertex buffer with the specified kind is updatable
  34891. */
  34892. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  34893. var vb = this._vertexBuffers[kind];
  34894. if (!vb) {
  34895. return false;
  34896. }
  34897. return vb.isUpdatable();
  34898. };
  34899. /**
  34900. * Gets a specific vertex buffer
  34901. * @param kind defines the data kind (Position, normal, etc...)
  34902. * @returns a {BABYLON.VertexBuffer}
  34903. */
  34904. Geometry.prototype.getVertexBuffer = function (kind) {
  34905. if (!this.isReady()) {
  34906. return null;
  34907. }
  34908. return this._vertexBuffers[kind];
  34909. };
  34910. /**
  34911. * Returns all vertex buffers
  34912. * @return an object holding all vertex buffers indexed by kind
  34913. */
  34914. Geometry.prototype.getVertexBuffers = function () {
  34915. if (!this.isReady()) {
  34916. return null;
  34917. }
  34918. return this._vertexBuffers;
  34919. };
  34920. /**
  34921. * Gets a boolean indicating if specific vertex buffer is present
  34922. * @param kind defines the data kind (Position, normal, etc...)
  34923. * @returns true if data is present
  34924. */
  34925. Geometry.prototype.isVerticesDataPresent = function (kind) {
  34926. if (!this._vertexBuffers) {
  34927. if (this._delayInfo) {
  34928. return this._delayInfo.indexOf(kind) !== -1;
  34929. }
  34930. return false;
  34931. }
  34932. return this._vertexBuffers[kind] !== undefined;
  34933. };
  34934. /**
  34935. * Gets a list of all attached data kinds (Position, normal, etc...)
  34936. * @returns a list of string containing all kinds
  34937. */
  34938. Geometry.prototype.getVerticesDataKinds = function () {
  34939. var result = [];
  34940. var kind;
  34941. if (!this._vertexBuffers && this._delayInfo) {
  34942. for (kind in this._delayInfo) {
  34943. result.push(kind);
  34944. }
  34945. }
  34946. else {
  34947. for (kind in this._vertexBuffers) {
  34948. result.push(kind);
  34949. }
  34950. }
  34951. return result;
  34952. };
  34953. /**
  34954. * Update index buffer
  34955. * @param indices defines the indices to store in the index buffer
  34956. * @param offset defines the offset in the target buffer where to store the data
  34957. */
  34958. Geometry.prototype.updateIndices = function (indices, offset) {
  34959. if (!this._indexBuffer) {
  34960. return;
  34961. }
  34962. if (!this._indexBufferIsUpdatable) {
  34963. this.setIndices(indices, null, true);
  34964. }
  34965. else {
  34966. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  34967. }
  34968. };
  34969. /**
  34970. * Creates a new index buffer
  34971. * @param indices defines the indices to store in the index buffer
  34972. * @param totalVertices defines the total number of vertices (could be null)
  34973. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  34974. */
  34975. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  34976. if (totalVertices === void 0) { totalVertices = null; }
  34977. if (updatable === void 0) { updatable = false; }
  34978. if (this._indexBuffer) {
  34979. this._engine._releaseBuffer(this._indexBuffer);
  34980. }
  34981. this._disposeVertexArrayObjects();
  34982. this._indices = indices;
  34983. this._indexBufferIsUpdatable = updatable;
  34984. if (this._meshes.length !== 0 && this._indices) {
  34985. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  34986. }
  34987. if (totalVertices != undefined) {
  34988. this._totalVertices = totalVertices;
  34989. }
  34990. var meshes = this._meshes;
  34991. var numOfMeshes = meshes.length;
  34992. for (var index = 0; index < numOfMeshes; index++) {
  34993. meshes[index]._createGlobalSubMesh(true);
  34994. }
  34995. this.notifyUpdate();
  34996. };
  34997. /**
  34998. * Return the total number of indices
  34999. * @returns the total number of indices
  35000. */
  35001. Geometry.prototype.getTotalIndices = function () {
  35002. if (!this.isReady()) {
  35003. return 0;
  35004. }
  35005. return this._indices.length;
  35006. };
  35007. /**
  35008. * Gets the index buffer array
  35009. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35010. * @returns the index buffer array
  35011. */
  35012. Geometry.prototype.getIndices = function (copyWhenShared) {
  35013. if (!this.isReady()) {
  35014. return null;
  35015. }
  35016. var orig = this._indices;
  35017. if (!copyWhenShared || this._meshes.length === 1) {
  35018. return orig;
  35019. }
  35020. else {
  35021. var len = orig.length;
  35022. var copy = [];
  35023. for (var i = 0; i < len; i++) {
  35024. copy.push(orig[i]);
  35025. }
  35026. return copy;
  35027. }
  35028. };
  35029. /**
  35030. * Gets the index buffer
  35031. * @return the index buffer
  35032. */
  35033. Geometry.prototype.getIndexBuffer = function () {
  35034. if (!this.isReady()) {
  35035. return null;
  35036. }
  35037. return this._indexBuffer;
  35038. };
  35039. /** @ignore */
  35040. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  35041. if (effect === void 0) { effect = null; }
  35042. if (!effect || !this._vertexArrayObjects) {
  35043. return;
  35044. }
  35045. if (this._vertexArrayObjects[effect.key]) {
  35046. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  35047. delete this._vertexArrayObjects[effect.key];
  35048. }
  35049. };
  35050. /**
  35051. * Release the associated resources for a specific mesh
  35052. * @param mesh defines the source mesh
  35053. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  35054. */
  35055. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35056. var meshes = this._meshes;
  35057. var index = meshes.indexOf(mesh);
  35058. if (index === -1) {
  35059. return;
  35060. }
  35061. meshes.splice(index, 1);
  35062. mesh._geometry = null;
  35063. if (meshes.length === 0 && shouldDispose) {
  35064. this.dispose();
  35065. }
  35066. };
  35067. /**
  35068. * Apply current geometry to a given mesh
  35069. * @param mesh defines the mesh to apply geometry to
  35070. */
  35071. Geometry.prototype.applyToMesh = function (mesh) {
  35072. if (mesh._geometry === this) {
  35073. return;
  35074. }
  35075. var previousGeometry = mesh._geometry;
  35076. if (previousGeometry) {
  35077. previousGeometry.releaseForMesh(mesh);
  35078. }
  35079. var meshes = this._meshes;
  35080. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35081. mesh._geometry = this;
  35082. this._scene.pushGeometry(this);
  35083. meshes.push(mesh);
  35084. if (this.isReady()) {
  35085. this._applyToMesh(mesh);
  35086. }
  35087. else {
  35088. mesh._boundingInfo = this._boundingInfo;
  35089. }
  35090. };
  35091. Geometry.prototype.updateExtend = function (data, stride) {
  35092. if (data === void 0) { data = null; }
  35093. if (!data) {
  35094. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35095. }
  35096. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35097. };
  35098. Geometry.prototype._applyToMesh = function (mesh) {
  35099. var numOfMeshes = this._meshes.length;
  35100. // vertexBuffers
  35101. for (var kind in this._vertexBuffers) {
  35102. if (numOfMeshes === 1) {
  35103. this._vertexBuffers[kind].create();
  35104. }
  35105. var buffer = this._vertexBuffers[kind].getBuffer();
  35106. if (buffer)
  35107. buffer.references = numOfMeshes;
  35108. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35109. if (!this._extend) {
  35110. this.updateExtend(this._vertexBuffers[kind].getData());
  35111. }
  35112. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35113. mesh._createGlobalSubMesh(false);
  35114. //bounding info was just created again, world matrix should be applied again.
  35115. mesh._updateBoundingInfo();
  35116. }
  35117. }
  35118. // indexBuffer
  35119. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35120. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35121. }
  35122. if (this._indexBuffer) {
  35123. this._indexBuffer.references = numOfMeshes;
  35124. }
  35125. };
  35126. Geometry.prototype.notifyUpdate = function (kind) {
  35127. if (this.onGeometryUpdated) {
  35128. this.onGeometryUpdated(this, kind);
  35129. }
  35130. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35131. var mesh = _a[_i];
  35132. mesh._markSubMeshesAsAttributesDirty();
  35133. }
  35134. };
  35135. /**
  35136. * Load the geometry if it was flagged as delay loaded
  35137. * @param scene defines the hosting scene
  35138. * @param onLoaded defines a callback called when the geometry is loaded
  35139. */
  35140. Geometry.prototype.load = function (scene, onLoaded) {
  35141. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35142. return;
  35143. }
  35144. if (this.isReady()) {
  35145. if (onLoaded) {
  35146. onLoaded();
  35147. }
  35148. return;
  35149. }
  35150. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35151. this._queueLoad(scene, onLoaded);
  35152. };
  35153. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35154. var _this = this;
  35155. if (!this.delayLoadingFile) {
  35156. return;
  35157. }
  35158. scene._addPendingData(this);
  35159. scene._loadFile(this.delayLoadingFile, function (data) {
  35160. if (!_this._delayLoadingFunction) {
  35161. return;
  35162. }
  35163. _this._delayLoadingFunction(JSON.parse(data), _this);
  35164. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35165. _this._delayInfo = [];
  35166. scene._removePendingData(_this);
  35167. var meshes = _this._meshes;
  35168. var numOfMeshes = meshes.length;
  35169. for (var index = 0; index < numOfMeshes; index++) {
  35170. _this._applyToMesh(meshes[index]);
  35171. }
  35172. if (onLoaded) {
  35173. onLoaded();
  35174. }
  35175. }, undefined, true);
  35176. };
  35177. /**
  35178. * Invert the geometry to move from a right handed system to a left handed one.
  35179. */
  35180. Geometry.prototype.toLeftHanded = function () {
  35181. // Flip faces
  35182. var tIndices = this.getIndices(false);
  35183. if (tIndices != null && tIndices.length > 0) {
  35184. for (var i = 0; i < tIndices.length; i += 3) {
  35185. var tTemp = tIndices[i + 0];
  35186. tIndices[i + 0] = tIndices[i + 2];
  35187. tIndices[i + 2] = tTemp;
  35188. }
  35189. this.setIndices(tIndices);
  35190. }
  35191. // Negate position.z
  35192. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35193. if (tPositions != null && tPositions.length > 0) {
  35194. for (var i = 0; i < tPositions.length; i += 3) {
  35195. tPositions[i + 2] = -tPositions[i + 2];
  35196. }
  35197. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35198. }
  35199. // Negate normal.z
  35200. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35201. if (tNormals != null && tNormals.length > 0) {
  35202. for (var i = 0; i < tNormals.length; i += 3) {
  35203. tNormals[i + 2] = -tNormals[i + 2];
  35204. }
  35205. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35206. }
  35207. };
  35208. // Cache
  35209. /** @ignore */
  35210. Geometry.prototype._resetPointsArrayCache = function () {
  35211. this._positions = null;
  35212. };
  35213. /** @ignore */
  35214. Geometry.prototype._generatePointsArray = function () {
  35215. if (this._positions)
  35216. return true;
  35217. this._positions = [];
  35218. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35219. if (!data) {
  35220. return false;
  35221. }
  35222. for (var index = 0; index < data.length; index += 3) {
  35223. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35224. }
  35225. return true;
  35226. };
  35227. /**
  35228. * Gets a value indicating if the geometry is disposed
  35229. * @returns true if the geometry was disposed
  35230. */
  35231. Geometry.prototype.isDisposed = function () {
  35232. return this._isDisposed;
  35233. };
  35234. Geometry.prototype._disposeVertexArrayObjects = function () {
  35235. if (this._vertexArrayObjects) {
  35236. for (var kind in this._vertexArrayObjects) {
  35237. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35238. }
  35239. this._vertexArrayObjects = {};
  35240. }
  35241. };
  35242. /**
  35243. * Free all associated resources
  35244. */
  35245. Geometry.prototype.dispose = function () {
  35246. var meshes = this._meshes;
  35247. var numOfMeshes = meshes.length;
  35248. var index;
  35249. for (index = 0; index < numOfMeshes; index++) {
  35250. this.releaseForMesh(meshes[index]);
  35251. }
  35252. this._meshes = [];
  35253. this._disposeVertexArrayObjects();
  35254. for (var kind in this._vertexBuffers) {
  35255. this._vertexBuffers[kind].dispose();
  35256. }
  35257. this._vertexBuffers = {};
  35258. this._totalVertices = 0;
  35259. if (this._indexBuffer) {
  35260. this._engine._releaseBuffer(this._indexBuffer);
  35261. }
  35262. this._indexBuffer = null;
  35263. this._indices = [];
  35264. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35265. this.delayLoadingFile = null;
  35266. this._delayLoadingFunction = null;
  35267. this._delayInfo = [];
  35268. this._boundingInfo = null;
  35269. this._scene.removeGeometry(this);
  35270. this._isDisposed = true;
  35271. };
  35272. /**
  35273. * Clone the current geometry into a new geometry
  35274. * @param id defines the unique ID of the new geometry
  35275. * @returns a new geometry object
  35276. */
  35277. Geometry.prototype.copy = function (id) {
  35278. var vertexData = new BABYLON.VertexData();
  35279. vertexData.indices = [];
  35280. var indices = this.getIndices();
  35281. if (indices) {
  35282. for (var index = 0; index < indices.length; index++) {
  35283. vertexData.indices.push(indices[index]);
  35284. }
  35285. }
  35286. var updatable = false;
  35287. var stopChecking = false;
  35288. var kind;
  35289. for (kind in this._vertexBuffers) {
  35290. // using slice() to make a copy of the array and not just reference it
  35291. var data = this.getVerticesData(kind);
  35292. if (data instanceof Float32Array) {
  35293. vertexData.set(new Float32Array(data), kind);
  35294. }
  35295. else {
  35296. vertexData.set(data.slice(0), kind);
  35297. }
  35298. if (!stopChecking) {
  35299. var vb = this.getVertexBuffer(kind);
  35300. if (vb) {
  35301. updatable = vb.isUpdatable();
  35302. stopChecking = !updatable;
  35303. }
  35304. }
  35305. }
  35306. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35307. geometry.delayLoadState = this.delayLoadState;
  35308. geometry.delayLoadingFile = this.delayLoadingFile;
  35309. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35310. for (kind in this._delayInfo) {
  35311. geometry._delayInfo = geometry._delayInfo || [];
  35312. geometry._delayInfo.push(kind);
  35313. }
  35314. // Bounding info
  35315. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35316. return geometry;
  35317. };
  35318. /**
  35319. * Serialize the current geometry info (and not the vertices data) into a JSON object
  35320. * @return a JSON representation of the current geometry data (without the vertices data)
  35321. */
  35322. Geometry.prototype.serialize = function () {
  35323. var serializationObject = {};
  35324. serializationObject.id = this.id;
  35325. serializationObject.updatable = this._updatable;
  35326. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35327. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35328. }
  35329. return serializationObject;
  35330. };
  35331. Geometry.prototype.toNumberArray = function (origin) {
  35332. if (Array.isArray(origin)) {
  35333. return origin;
  35334. }
  35335. else {
  35336. return Array.prototype.slice.call(origin);
  35337. }
  35338. };
  35339. /**
  35340. * Serialize all vertices data into a JSON oject
  35341. * @returns a JSON representation of the current geometry data
  35342. */
  35343. Geometry.prototype.serializeVerticeData = function () {
  35344. var serializationObject = this.serialize();
  35345. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35346. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  35347. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35348. serializationObject.positions._updatable = true;
  35349. }
  35350. }
  35351. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35352. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  35353. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35354. serializationObject.normals._updatable = true;
  35355. }
  35356. }
  35357. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35358. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  35359. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  35360. serializationObject.tangets._updatable = true;
  35361. }
  35362. }
  35363. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35364. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  35365. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  35366. serializationObject.uvs._updatable = true;
  35367. }
  35368. }
  35369. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35370. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  35371. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  35372. serializationObject.uv2s._updatable = true;
  35373. }
  35374. }
  35375. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35376. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  35377. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  35378. serializationObject.uv3s._updatable = true;
  35379. }
  35380. }
  35381. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35382. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  35383. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  35384. serializationObject.uv4s._updatable = true;
  35385. }
  35386. }
  35387. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35388. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  35389. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  35390. serializationObject.uv5s._updatable = true;
  35391. }
  35392. }
  35393. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35394. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  35395. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  35396. serializationObject.uv6s._updatable = true;
  35397. }
  35398. }
  35399. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35400. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  35401. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  35402. serializationObject.colors._updatable = true;
  35403. }
  35404. }
  35405. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35406. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  35407. serializationObject.matricesIndices._isExpanded = true;
  35408. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35409. serializationObject.matricesIndices._updatable = true;
  35410. }
  35411. }
  35412. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35413. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  35414. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35415. serializationObject.matricesWeights._updatable = true;
  35416. }
  35417. }
  35418. serializationObject.indices = this.toNumberArray(this.getIndices());
  35419. return serializationObject;
  35420. };
  35421. // Statics
  35422. /**
  35423. * Extracts a clone of a mesh geometry
  35424. * @param mesh defines the source mesh
  35425. * @param id defines the unique ID of the new geometry object
  35426. * @returns the new geometry object
  35427. */
  35428. Geometry.ExtractFromMesh = function (mesh, id) {
  35429. var geometry = mesh._geometry;
  35430. if (!geometry) {
  35431. return null;
  35432. }
  35433. return geometry.copy(id);
  35434. };
  35435. /**
  35436. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  35437. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  35438. * Be aware Math.random() could cause collisions, but:
  35439. * "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"
  35440. * @returns a string containing a new GUID
  35441. */
  35442. Geometry.RandomId = function () {
  35443. return BABYLON.Tools.RandomId();
  35444. };
  35445. /** @ignore */
  35446. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  35447. var scene = mesh.getScene();
  35448. // Geometry
  35449. var geometryId = parsedGeometry.geometryId;
  35450. if (geometryId) {
  35451. var geometry = scene.getGeometryByID(geometryId);
  35452. if (geometry) {
  35453. geometry.applyToMesh(mesh);
  35454. }
  35455. }
  35456. else if (parsedGeometry instanceof ArrayBuffer) {
  35457. var binaryInfo = mesh._binaryInfo;
  35458. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  35459. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  35460. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  35461. }
  35462. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  35463. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  35464. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  35465. }
  35466. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  35467. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  35468. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  35469. }
  35470. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  35471. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  35472. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  35473. }
  35474. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  35475. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  35476. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  35477. }
  35478. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  35479. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  35480. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  35481. }
  35482. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  35483. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  35484. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  35485. }
  35486. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  35487. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  35488. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  35489. }
  35490. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  35491. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  35492. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  35493. }
  35494. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  35495. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  35496. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  35497. }
  35498. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  35499. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  35500. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  35501. }
  35502. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  35503. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  35504. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  35505. }
  35506. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  35507. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  35508. mesh.setIndices(indicesData, null);
  35509. }
  35510. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  35511. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  35512. mesh.subMeshes = [];
  35513. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  35514. var materialIndex = subMeshesData[(i * 5) + 0];
  35515. var verticesStart = subMeshesData[(i * 5) + 1];
  35516. var verticesCount = subMeshesData[(i * 5) + 2];
  35517. var indexStart = subMeshesData[(i * 5) + 3];
  35518. var indexCount = subMeshesData[(i * 5) + 4];
  35519. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  35520. }
  35521. }
  35522. }
  35523. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  35524. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  35525. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  35526. if (parsedGeometry.tangents) {
  35527. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  35528. }
  35529. if (parsedGeometry.uvs) {
  35530. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  35531. }
  35532. if (parsedGeometry.uvs2) {
  35533. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  35534. }
  35535. if (parsedGeometry.uvs3) {
  35536. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  35537. }
  35538. if (parsedGeometry.uvs4) {
  35539. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  35540. }
  35541. if (parsedGeometry.uvs5) {
  35542. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  35543. }
  35544. if (parsedGeometry.uvs6) {
  35545. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  35546. }
  35547. if (parsedGeometry.colors) {
  35548. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  35549. }
  35550. if (parsedGeometry.matricesIndices) {
  35551. if (!parsedGeometry.matricesIndices._isExpanded) {
  35552. var floatIndices = [];
  35553. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  35554. var matricesIndex = parsedGeometry.matricesIndices[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.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  35561. }
  35562. else {
  35563. delete parsedGeometry.matricesIndices._isExpanded;
  35564. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  35565. }
  35566. }
  35567. if (parsedGeometry.matricesIndicesExtra) {
  35568. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  35569. var floatIndices = [];
  35570. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  35571. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  35572. floatIndices.push(matricesIndex & 0x000000FF);
  35573. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35574. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35575. floatIndices.push(matricesIndex >> 24);
  35576. }
  35577. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  35578. }
  35579. else {
  35580. delete parsedGeometry.matricesIndices._isExpanded;
  35581. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  35582. }
  35583. }
  35584. if (parsedGeometry.matricesWeights) {
  35585. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  35586. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  35587. }
  35588. if (parsedGeometry.matricesWeightsExtra) {
  35589. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  35590. }
  35591. mesh.setIndices(parsedGeometry.indices, null);
  35592. }
  35593. // SubMeshes
  35594. if (parsedGeometry.subMeshes) {
  35595. mesh.subMeshes = [];
  35596. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  35597. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  35598. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  35599. }
  35600. }
  35601. // Flat shading
  35602. if (mesh._shouldGenerateFlatShading) {
  35603. mesh.convertToFlatShadedMesh();
  35604. delete mesh._shouldGenerateFlatShading;
  35605. }
  35606. // Update
  35607. mesh.computeWorldMatrix(true);
  35608. // Octree
  35609. var sceneOctree = scene.selectionOctree;
  35610. if (sceneOctree !== undefined && sceneOctree !== null) {
  35611. sceneOctree.addMesh(mesh);
  35612. }
  35613. };
  35614. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  35615. var epsilon = 1e-3;
  35616. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  35617. return;
  35618. }
  35619. var noInfluenceBoneIndex = 0.0;
  35620. if (parsedGeometry.skeletonId > -1) {
  35621. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  35622. if (!skeleton) {
  35623. return;
  35624. }
  35625. noInfluenceBoneIndex = skeleton.bones.length;
  35626. }
  35627. else {
  35628. return;
  35629. }
  35630. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35631. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35632. var matricesWeights = parsedGeometry.matricesWeights;
  35633. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  35634. var influencers = parsedGeometry.numBoneInfluencer;
  35635. var size = matricesWeights.length;
  35636. for (var i = 0; i < size; i += 4) {
  35637. var weight = 0.0;
  35638. var firstZeroWeight = -1;
  35639. for (var j = 0; j < 4; j++) {
  35640. var w = matricesWeights[i + j];
  35641. weight += w;
  35642. if (w < epsilon && firstZeroWeight < 0) {
  35643. firstZeroWeight = j;
  35644. }
  35645. }
  35646. if (matricesWeightsExtra) {
  35647. for (var j = 0; j < 4; j++) {
  35648. var w = matricesWeightsExtra[i + j];
  35649. weight += w;
  35650. if (w < epsilon && firstZeroWeight < 0) {
  35651. firstZeroWeight = j + 4;
  35652. }
  35653. }
  35654. }
  35655. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  35656. firstZeroWeight = influencers - 1;
  35657. }
  35658. if (weight > epsilon) {
  35659. var mweight = 1.0 / weight;
  35660. for (var j = 0; j < 4; j++) {
  35661. matricesWeights[i + j] *= mweight;
  35662. }
  35663. if (matricesWeightsExtra) {
  35664. for (var j = 0; j < 4; j++) {
  35665. matricesWeightsExtra[i + j] *= mweight;
  35666. }
  35667. }
  35668. }
  35669. else {
  35670. if (firstZeroWeight >= 4) {
  35671. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  35672. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  35673. }
  35674. else {
  35675. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  35676. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  35677. }
  35678. }
  35679. }
  35680. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  35681. if (parsedGeometry.matricesWeightsExtra) {
  35682. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  35683. }
  35684. };
  35685. /**
  35686. * Create a new geometry from persisted data (Using .babylon file format)
  35687. * @param parsedVertexData defines the persisted data
  35688. * @param scene defines the hosting scene
  35689. * @param rootUrl defines the root url to use to load assets (like delayed data)
  35690. * @returns the new geometry object
  35691. */
  35692. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35693. if (scene.getGeometryByID(parsedVertexData.id)) {
  35694. return null; // null since geometry could be something else than a box...
  35695. }
  35696. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  35697. if (BABYLON.Tags) {
  35698. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35699. }
  35700. if (parsedVertexData.delayLoadingFile) {
  35701. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35702. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35703. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35704. geometry._delayInfo = [];
  35705. if (parsedVertexData.hasUVs) {
  35706. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35707. }
  35708. if (parsedVertexData.hasUVs2) {
  35709. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35710. }
  35711. if (parsedVertexData.hasUVs3) {
  35712. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35713. }
  35714. if (parsedVertexData.hasUVs4) {
  35715. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35716. }
  35717. if (parsedVertexData.hasUVs5) {
  35718. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35719. }
  35720. if (parsedVertexData.hasUVs6) {
  35721. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35722. }
  35723. if (parsedVertexData.hasColors) {
  35724. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35725. }
  35726. if (parsedVertexData.hasMatricesIndices) {
  35727. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35728. }
  35729. if (parsedVertexData.hasMatricesWeights) {
  35730. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35731. }
  35732. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35733. }
  35734. else {
  35735. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35736. }
  35737. scene.pushGeometry(geometry, true);
  35738. return geometry;
  35739. };
  35740. return Geometry;
  35741. }());
  35742. BABYLON.Geometry = Geometry;
  35743. // Primitives
  35744. /// Abstract class
  35745. /**
  35746. * Abstract class used to provide common services for all typed geometries
  35747. */
  35748. var _PrimitiveGeometry = /** @class */ (function (_super) {
  35749. __extends(_PrimitiveGeometry, _super);
  35750. /**
  35751. * Creates a new typed geometry
  35752. * @param id defines the unique ID of the geometry
  35753. * @param scene defines the hosting scene
  35754. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35755. * @param mesh defines the hosting mesh (can be null)
  35756. */
  35757. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  35758. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  35759. if (mesh === void 0) { mesh = null; }
  35760. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  35761. _this._canBeRegenerated = _canBeRegenerated;
  35762. _this._beingRegenerated = true;
  35763. _this.regenerate();
  35764. _this._beingRegenerated = false;
  35765. return _this;
  35766. }
  35767. /**
  35768. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  35769. * @returns true if the geometry can be regenerated
  35770. */
  35771. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  35772. return this._canBeRegenerated;
  35773. };
  35774. /**
  35775. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  35776. */
  35777. _PrimitiveGeometry.prototype.regenerate = function () {
  35778. if (!this._canBeRegenerated) {
  35779. return;
  35780. }
  35781. this._beingRegenerated = true;
  35782. this.setAllVerticesData(this._regenerateVertexData(), false);
  35783. this._beingRegenerated = false;
  35784. };
  35785. /**
  35786. * Clone the geometry
  35787. * @param id defines the unique ID of the new geometry
  35788. * @returns the new geometry
  35789. */
  35790. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  35791. return _super.prototype.copy.call(this, id);
  35792. };
  35793. // overrides
  35794. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35795. if (!this._beingRegenerated) {
  35796. return;
  35797. }
  35798. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35799. };
  35800. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  35801. if (!this._beingRegenerated) {
  35802. return;
  35803. }
  35804. _super.prototype.setVerticesData.call(this, kind, data, false);
  35805. };
  35806. // to override
  35807. /** @ignore */
  35808. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  35809. throw new Error("Abstract method");
  35810. };
  35811. _PrimitiveGeometry.prototype.copy = function (id) {
  35812. throw new Error("Must be overriden in sub-classes.");
  35813. };
  35814. _PrimitiveGeometry.prototype.serialize = function () {
  35815. var serializationObject = _super.prototype.serialize.call(this);
  35816. serializationObject.canBeRegenerated = this.canBeRegenerated();
  35817. return serializationObject;
  35818. };
  35819. return _PrimitiveGeometry;
  35820. }(Geometry));
  35821. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  35822. /**
  35823. * Creates a ribbon geometry
  35824. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  35825. */
  35826. var RibbonGeometry = /** @class */ (function (_super) {
  35827. __extends(RibbonGeometry, _super);
  35828. /**
  35829. * Creates a ribbon geometry
  35830. * @param id defines the unique ID of the geometry
  35831. * @param scene defines the hosting scene
  35832. * @param pathArray defines the array of paths to use
  35833. * @param closeArray defines if the last path and the first path must be joined
  35834. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  35835. * @param offset defines the offset between points
  35836. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35837. * @param mesh defines the hosting mesh (can be null)
  35838. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35839. */
  35840. function RibbonGeometry(id, scene,
  35841. /**
  35842. * Defines the array of paths to use
  35843. */
  35844. pathArray,
  35845. /**
  35846. * Defines if the last and first points of each path in your pathArray must be joined
  35847. */
  35848. closeArray,
  35849. /**
  35850. * Defines if the last and first points of each path in your pathArray must be joined
  35851. */
  35852. closePath,
  35853. /**
  35854. * Defines the offset between points
  35855. */
  35856. offset, canBeRegenerated, mesh,
  35857. /**
  35858. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35859. */
  35860. side) {
  35861. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35862. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35863. _this.pathArray = pathArray;
  35864. _this.closeArray = closeArray;
  35865. _this.closePath = closePath;
  35866. _this.offset = offset;
  35867. _this.side = side;
  35868. return _this;
  35869. }
  35870. /** @ignore */
  35871. RibbonGeometry.prototype._regenerateVertexData = function () {
  35872. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  35873. };
  35874. RibbonGeometry.prototype.copy = function (id) {
  35875. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  35876. };
  35877. return RibbonGeometry;
  35878. }(_PrimitiveGeometry));
  35879. BABYLON.RibbonGeometry = RibbonGeometry;
  35880. /**
  35881. * Creates a box geometry
  35882. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  35883. */
  35884. var BoxGeometry = /** @class */ (function (_super) {
  35885. __extends(BoxGeometry, _super);
  35886. /**
  35887. * Creates a box geometry
  35888. * @param id defines the unique ID of the geometry
  35889. * @param scene defines the hosting scene
  35890. * @param size defines the zise of the box (width, height and depth are the same)
  35891. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35892. * @param mesh defines the hosting mesh (can be null)
  35893. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35894. */
  35895. function BoxGeometry(id, scene,
  35896. /**
  35897. * Defines the zise of the box (width, height and depth are the same)
  35898. */
  35899. size, canBeRegenerated, mesh,
  35900. /**
  35901. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35902. */
  35903. side) {
  35904. if (mesh === void 0) { mesh = null; }
  35905. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35906. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35907. _this.size = size;
  35908. _this.side = side;
  35909. return _this;
  35910. }
  35911. BoxGeometry.prototype._regenerateVertexData = function () {
  35912. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  35913. };
  35914. BoxGeometry.prototype.copy = function (id) {
  35915. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  35916. };
  35917. BoxGeometry.prototype.serialize = function () {
  35918. var serializationObject = _super.prototype.serialize.call(this);
  35919. serializationObject.size = this.size;
  35920. return serializationObject;
  35921. };
  35922. BoxGeometry.Parse = function (parsedBox, scene) {
  35923. if (scene.getGeometryByID(parsedBox.id)) {
  35924. return null; // null since geometry could be something else than a box...
  35925. }
  35926. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  35927. if (BABYLON.Tags) {
  35928. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  35929. }
  35930. scene.pushGeometry(box, true);
  35931. return box;
  35932. };
  35933. return BoxGeometry;
  35934. }(_PrimitiveGeometry));
  35935. BABYLON.BoxGeometry = BoxGeometry;
  35936. /**
  35937. * Creates a sphere geometry
  35938. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  35939. */
  35940. var SphereGeometry = /** @class */ (function (_super) {
  35941. __extends(SphereGeometry, _super);
  35942. /**
  35943. * Create a new sphere geometry
  35944. * @param id defines the unique ID of the geometry
  35945. * @param scene defines the hosting scene
  35946. * @param segments defines the number of segments to use to create the sphere
  35947. * @param diameter defines the diameter of the sphere
  35948. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35949. * @param mesh defines the hosting mesh (can be null)
  35950. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35951. */
  35952. function SphereGeometry(id, scene,
  35953. /**
  35954. * Defines the number of segments to use to create the sphere
  35955. */
  35956. segments,
  35957. /**
  35958. * Defines the diameter of the sphere
  35959. */
  35960. diameter, canBeRegenerated, mesh,
  35961. /**
  35962. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35963. */
  35964. side) {
  35965. if (mesh === void 0) { mesh = null; }
  35966. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35967. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35968. _this.segments = segments;
  35969. _this.diameter = diameter;
  35970. _this.side = side;
  35971. return _this;
  35972. }
  35973. SphereGeometry.prototype._regenerateVertexData = function () {
  35974. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  35975. };
  35976. SphereGeometry.prototype.copy = function (id) {
  35977. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  35978. };
  35979. SphereGeometry.prototype.serialize = function () {
  35980. var serializationObject = _super.prototype.serialize.call(this);
  35981. serializationObject.segments = this.segments;
  35982. serializationObject.diameter = this.diameter;
  35983. return serializationObject;
  35984. };
  35985. SphereGeometry.Parse = function (parsedSphere, scene) {
  35986. if (scene.getGeometryByID(parsedSphere.id)) {
  35987. return null; // null since geometry could be something else than a sphere...
  35988. }
  35989. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  35990. if (BABYLON.Tags) {
  35991. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  35992. }
  35993. scene.pushGeometry(sphere, true);
  35994. return sphere;
  35995. };
  35996. return SphereGeometry;
  35997. }(_PrimitiveGeometry));
  35998. BABYLON.SphereGeometry = SphereGeometry;
  35999. /**
  36000. * Creates a disc geometry
  36001. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  36002. */
  36003. var DiscGeometry = /** @class */ (function (_super) {
  36004. __extends(DiscGeometry, _super);
  36005. /**
  36006. * Creates a new disc geometry
  36007. * @param id defines the unique ID of the geometry
  36008. * @param scene defines the hosting scene
  36009. * @param radius defines the radius of the disc
  36010. * @param tessellation defines the tesselation factor to apply to the disc
  36011. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36012. * @param mesh defines the hosting mesh (can be null)
  36013. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36014. */
  36015. function DiscGeometry(id, scene,
  36016. /**
  36017. * Defines the radius of the disc
  36018. */
  36019. radius,
  36020. /**
  36021. * Defines the tesselation factor to apply to the disc
  36022. */
  36023. tessellation, canBeRegenerated, mesh,
  36024. /**
  36025. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36026. */
  36027. side) {
  36028. if (mesh === void 0) { mesh = null; }
  36029. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36030. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36031. _this.radius = radius;
  36032. _this.tessellation = tessellation;
  36033. _this.side = side;
  36034. return _this;
  36035. }
  36036. DiscGeometry.prototype._regenerateVertexData = function () {
  36037. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36038. };
  36039. DiscGeometry.prototype.copy = function (id) {
  36040. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36041. };
  36042. return DiscGeometry;
  36043. }(_PrimitiveGeometry));
  36044. BABYLON.DiscGeometry = DiscGeometry;
  36045. /**
  36046. * Creates a new cylinder geometry
  36047. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  36048. */
  36049. var CylinderGeometry = /** @class */ (function (_super) {
  36050. __extends(CylinderGeometry, _super);
  36051. /**
  36052. * Creates a new cylinder geometry
  36053. * @param id defines the unique ID of the geometry
  36054. * @param scene defines the hosting scene
  36055. * @param height defines the height of the cylinder
  36056. * @param diameterTop defines the diameter of the cylinder's top cap
  36057. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  36058. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  36059. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  36060. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36061. * @param mesh defines the hosting mesh (can be null)
  36062. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36063. */
  36064. function CylinderGeometry(id, scene,
  36065. /**
  36066. * Defines the height of the cylinder
  36067. */
  36068. height,
  36069. /**
  36070. * Defines the diameter of the cylinder's top cap
  36071. */
  36072. diameterTop,
  36073. /**
  36074. * Defines the diameter of the cylinder's bottom cap
  36075. */
  36076. diameterBottom,
  36077. /**
  36078. * Defines the tessellation factor to apply to the cylinder
  36079. */
  36080. tessellation,
  36081. /**
  36082. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36083. */
  36084. subdivisions, canBeRegenerated, mesh,
  36085. /**
  36086. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36087. */
  36088. side) {
  36089. if (subdivisions === void 0) { subdivisions = 1; }
  36090. if (mesh === void 0) { mesh = null; }
  36091. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36092. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36093. _this.height = height;
  36094. _this.diameterTop = diameterTop;
  36095. _this.diameterBottom = diameterBottom;
  36096. _this.tessellation = tessellation;
  36097. _this.subdivisions = subdivisions;
  36098. _this.side = side;
  36099. return _this;
  36100. }
  36101. CylinderGeometry.prototype._regenerateVertexData = function () {
  36102. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36103. };
  36104. CylinderGeometry.prototype.copy = function (id) {
  36105. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36106. };
  36107. CylinderGeometry.prototype.serialize = function () {
  36108. var serializationObject = _super.prototype.serialize.call(this);
  36109. serializationObject.height = this.height;
  36110. serializationObject.diameterTop = this.diameterTop;
  36111. serializationObject.diameterBottom = this.diameterBottom;
  36112. serializationObject.tessellation = this.tessellation;
  36113. return serializationObject;
  36114. };
  36115. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36116. if (scene.getGeometryByID(parsedCylinder.id)) {
  36117. return null; // null since geometry could be something else than a cylinder...
  36118. }
  36119. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36120. if (BABYLON.Tags) {
  36121. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36122. }
  36123. scene.pushGeometry(cylinder, true);
  36124. return cylinder;
  36125. };
  36126. return CylinderGeometry;
  36127. }(_PrimitiveGeometry));
  36128. BABYLON.CylinderGeometry = CylinderGeometry;
  36129. /**
  36130. * Creates a new torus geometry
  36131. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36132. */
  36133. var TorusGeometry = /** @class */ (function (_super) {
  36134. __extends(TorusGeometry, _super);
  36135. /**
  36136. * Creates a new torus geometry
  36137. * @param id defines the unique ID of the geometry
  36138. * @param scene defines the hosting scene
  36139. * @param diameter defines the diameter of the torus
  36140. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36141. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36142. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36143. * @param mesh defines the hosting mesh (can be null)
  36144. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36145. */
  36146. function TorusGeometry(id, scene,
  36147. /**
  36148. * Defines the diameter of the torus
  36149. */
  36150. diameter,
  36151. /**
  36152. * Defines the thickness of the torus (ie. internal diameter)
  36153. */
  36154. thickness,
  36155. /**
  36156. * Defines the tesselation factor to apply to the torus
  36157. */
  36158. tessellation, canBeRegenerated, mesh,
  36159. /**
  36160. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36161. */
  36162. side) {
  36163. if (mesh === void 0) { mesh = null; }
  36164. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36165. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36166. _this.diameter = diameter;
  36167. _this.thickness = thickness;
  36168. _this.tessellation = tessellation;
  36169. _this.side = side;
  36170. return _this;
  36171. }
  36172. TorusGeometry.prototype._regenerateVertexData = function () {
  36173. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36174. };
  36175. TorusGeometry.prototype.copy = function (id) {
  36176. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36177. };
  36178. TorusGeometry.prototype.serialize = function () {
  36179. var serializationObject = _super.prototype.serialize.call(this);
  36180. serializationObject.diameter = this.diameter;
  36181. serializationObject.thickness = this.thickness;
  36182. serializationObject.tessellation = this.tessellation;
  36183. return serializationObject;
  36184. };
  36185. TorusGeometry.Parse = function (parsedTorus, scene) {
  36186. if (scene.getGeometryByID(parsedTorus.id)) {
  36187. return null; // null since geometry could be something else than a torus...
  36188. }
  36189. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36190. if (BABYLON.Tags) {
  36191. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36192. }
  36193. scene.pushGeometry(torus, true);
  36194. return torus;
  36195. };
  36196. return TorusGeometry;
  36197. }(_PrimitiveGeometry));
  36198. BABYLON.TorusGeometry = TorusGeometry;
  36199. /**
  36200. * Creates a new ground geometry
  36201. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36202. */
  36203. var GroundGeometry = /** @class */ (function (_super) {
  36204. __extends(GroundGeometry, _super);
  36205. /**
  36206. * Creates a new ground geometry
  36207. * @param id defines the unique ID of the geometry
  36208. * @param scene defines the hosting scene
  36209. * @param width defines the width of the ground
  36210. * @param height defines the height of the ground
  36211. * @param subdivisions defines the subdivisions to apply to the ground
  36212. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36213. * @param mesh defines the hosting mesh (can be null)
  36214. */
  36215. function GroundGeometry(id, scene,
  36216. /**
  36217. * Defines the width of the ground
  36218. */
  36219. width,
  36220. /**
  36221. * Defines the height of the ground
  36222. */
  36223. height,
  36224. /**
  36225. * Defines the subdivisions to apply to the ground
  36226. */
  36227. subdivisions, canBeRegenerated, mesh) {
  36228. if (mesh === void 0) { mesh = null; }
  36229. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36230. _this.width = width;
  36231. _this.height = height;
  36232. _this.subdivisions = subdivisions;
  36233. return _this;
  36234. }
  36235. GroundGeometry.prototype._regenerateVertexData = function () {
  36236. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36237. };
  36238. GroundGeometry.prototype.copy = function (id) {
  36239. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36240. };
  36241. GroundGeometry.prototype.serialize = function () {
  36242. var serializationObject = _super.prototype.serialize.call(this);
  36243. serializationObject.width = this.width;
  36244. serializationObject.height = this.height;
  36245. serializationObject.subdivisions = this.subdivisions;
  36246. return serializationObject;
  36247. };
  36248. GroundGeometry.Parse = function (parsedGround, scene) {
  36249. if (scene.getGeometryByID(parsedGround.id)) {
  36250. return null; // null since geometry could be something else than a ground...
  36251. }
  36252. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36253. if (BABYLON.Tags) {
  36254. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36255. }
  36256. scene.pushGeometry(ground, true);
  36257. return ground;
  36258. };
  36259. return GroundGeometry;
  36260. }(_PrimitiveGeometry));
  36261. BABYLON.GroundGeometry = GroundGeometry;
  36262. /**
  36263. * Creates a tiled ground geometry
  36264. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36265. */
  36266. var TiledGroundGeometry = /** @class */ (function (_super) {
  36267. __extends(TiledGroundGeometry, _super);
  36268. /**
  36269. * Creates a tiled ground geometry
  36270. * @param id defines the unique ID of the geometry
  36271. * @param scene defines the hosting scene
  36272. * @param xmin defines the minimum value on X axis
  36273. * @param zmin defines the minimum value on Z axis
  36274. * @param xmax defines the maximum value on X axis
  36275. * @param zmax defines the maximum value on Z axis
  36276. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36277. * @param precision defines the precision to use when computing the tiles
  36278. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36279. * @param mesh defines the hosting mesh (can be null)
  36280. */
  36281. function TiledGroundGeometry(id, scene,
  36282. /**
  36283. * Defines the minimum value on X axis
  36284. */
  36285. xmin,
  36286. /**
  36287. * Defines the minimum value on Z axis
  36288. */
  36289. zmin,
  36290. /**
  36291. * Defines the maximum value on X axis
  36292. */
  36293. xmax,
  36294. /**
  36295. * Defines the maximum value on Z axis
  36296. */
  36297. zmax,
  36298. /**
  36299. * Defines the subdivisions to apply to the ground
  36300. */
  36301. subdivisions,
  36302. /**
  36303. * Defines the precision to use when computing the tiles
  36304. */
  36305. precision, canBeRegenerated, mesh) {
  36306. if (mesh === void 0) { mesh = null; }
  36307. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36308. _this.xmin = xmin;
  36309. _this.zmin = zmin;
  36310. _this.xmax = xmax;
  36311. _this.zmax = zmax;
  36312. _this.subdivisions = subdivisions;
  36313. _this.precision = precision;
  36314. return _this;
  36315. }
  36316. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  36317. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36318. };
  36319. TiledGroundGeometry.prototype.copy = function (id) {
  36320. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36321. };
  36322. return TiledGroundGeometry;
  36323. }(_PrimitiveGeometry));
  36324. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  36325. /**
  36326. * Creates a plane geometry
  36327. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36328. */
  36329. var PlaneGeometry = /** @class */ (function (_super) {
  36330. __extends(PlaneGeometry, _super);
  36331. /**
  36332. * Creates a plane geometry
  36333. * @param id defines the unique ID of the geometry
  36334. * @param scene defines the hosting scene
  36335. * @param size defines the size of the plane (width === height)
  36336. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36337. * @param mesh defines the hosting mesh (can be null)
  36338. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36339. */
  36340. function PlaneGeometry(id, scene,
  36341. /**
  36342. * Defines the size of the plane (width === height)
  36343. */
  36344. size, canBeRegenerated, mesh,
  36345. /**
  36346. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36347. */
  36348. side) {
  36349. if (mesh === void 0) { mesh = null; }
  36350. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36351. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36352. _this.size = size;
  36353. _this.side = side;
  36354. return _this;
  36355. }
  36356. PlaneGeometry.prototype._regenerateVertexData = function () {
  36357. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36358. };
  36359. PlaneGeometry.prototype.copy = function (id) {
  36360. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36361. };
  36362. PlaneGeometry.prototype.serialize = function () {
  36363. var serializationObject = _super.prototype.serialize.call(this);
  36364. serializationObject.size = this.size;
  36365. return serializationObject;
  36366. };
  36367. PlaneGeometry.Parse = function (parsedPlane, scene) {
  36368. if (scene.getGeometryByID(parsedPlane.id)) {
  36369. return null; // null since geometry could be something else than a ground...
  36370. }
  36371. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36372. if (BABYLON.Tags) {
  36373. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36374. }
  36375. scene.pushGeometry(plane, true);
  36376. return plane;
  36377. };
  36378. return PlaneGeometry;
  36379. }(_PrimitiveGeometry));
  36380. BABYLON.PlaneGeometry = PlaneGeometry;
  36381. /**
  36382. * Creates a torus knot geometry
  36383. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  36384. */
  36385. var TorusKnotGeometry = /** @class */ (function (_super) {
  36386. __extends(TorusKnotGeometry, _super);
  36387. /**
  36388. * Creates a torus knot geometry
  36389. * @param id defines the unique ID of the geometry
  36390. * @param scene defines the hosting scene
  36391. * @param radius defines the radius of the torus knot
  36392. * @param tube defines the thickness of the torus knot tube
  36393. * @param radialSegments defines the number of radial segments
  36394. * @param tubularSegments defines the number of tubular segments
  36395. * @param p defines the first number of windings
  36396. * @param q defines the second number of windings
  36397. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36398. * @param mesh defines the hosting mesh (can be null)
  36399. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36400. */
  36401. function TorusKnotGeometry(id, scene,
  36402. /**
  36403. * Defines the radius of the torus knot
  36404. */
  36405. radius,
  36406. /**
  36407. * Defines the thickness of the torus knot tube
  36408. */
  36409. tube,
  36410. /**
  36411. * Defines the number of radial segments
  36412. */
  36413. radialSegments,
  36414. /**
  36415. * Defines the number of tubular segments
  36416. */
  36417. tubularSegments,
  36418. /**
  36419. * Defines the first number of windings
  36420. */
  36421. p,
  36422. /**
  36423. * Defines the second number of windings
  36424. */
  36425. q, canBeRegenerated, mesh,
  36426. /**
  36427. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36428. */
  36429. side) {
  36430. if (mesh === void 0) { mesh = null; }
  36431. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36432. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36433. _this.radius = radius;
  36434. _this.tube = tube;
  36435. _this.radialSegments = radialSegments;
  36436. _this.tubularSegments = tubularSegments;
  36437. _this.p = p;
  36438. _this.q = q;
  36439. _this.side = side;
  36440. return _this;
  36441. }
  36442. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  36443. 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 });
  36444. };
  36445. TorusKnotGeometry.prototype.copy = function (id) {
  36446. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  36447. };
  36448. TorusKnotGeometry.prototype.serialize = function () {
  36449. var serializationObject = _super.prototype.serialize.call(this);
  36450. serializationObject.radius = this.radius;
  36451. serializationObject.tube = this.tube;
  36452. serializationObject.radialSegments = this.radialSegments;
  36453. serializationObject.tubularSegments = this.tubularSegments;
  36454. serializationObject.p = this.p;
  36455. serializationObject.q = this.q;
  36456. return serializationObject;
  36457. };
  36458. ;
  36459. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  36460. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  36461. return null; // null since geometry could be something else than a ground...
  36462. }
  36463. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  36464. if (BABYLON.Tags) {
  36465. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  36466. }
  36467. scene.pushGeometry(torusKnot, true);
  36468. return torusKnot;
  36469. };
  36470. return TorusKnotGeometry;
  36471. }(_PrimitiveGeometry));
  36472. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  36473. //}
  36474. })(BABYLON || (BABYLON = {}));
  36475. //# sourceMappingURL=babylon.geometry.js.map
  36476. var BABYLON;
  36477. (function (BABYLON) {
  36478. /**
  36479. * PostProcessManager is used to manage one or more post processes or post process pipelines
  36480. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  36481. */
  36482. var PostProcessManager = /** @class */ (function () {
  36483. /**
  36484. * Creates a new instance of @see PostProcess
  36485. * @param scene The scene that the post process is associated with.
  36486. */
  36487. function PostProcessManager(scene) {
  36488. this._vertexBuffers = {};
  36489. this._scene = scene;
  36490. }
  36491. PostProcessManager.prototype._prepareBuffers = function () {
  36492. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  36493. return;
  36494. }
  36495. // VBO
  36496. var vertices = [];
  36497. vertices.push(1, 1);
  36498. vertices.push(-1, 1);
  36499. vertices.push(-1, -1);
  36500. vertices.push(1, -1);
  36501. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  36502. this._buildIndexBuffer();
  36503. };
  36504. PostProcessManager.prototype._buildIndexBuffer = function () {
  36505. // Indices
  36506. var indices = [];
  36507. indices.push(0);
  36508. indices.push(1);
  36509. indices.push(2);
  36510. indices.push(0);
  36511. indices.push(2);
  36512. indices.push(3);
  36513. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  36514. };
  36515. /**
  36516. * Rebuilds the vertex buffers of the manager.
  36517. */
  36518. PostProcessManager.prototype._rebuild = function () {
  36519. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36520. if (!vb) {
  36521. return;
  36522. }
  36523. vb._rebuild();
  36524. this._buildIndexBuffer();
  36525. };
  36526. // Methods
  36527. /**
  36528. * Prepares a frame to be run through a post process.
  36529. * @param sourceTexture The input texture to the post procesess. (default: null)
  36530. * @param postProcesses An array of post processes to be run. (default: null)
  36531. * @returns True if the post processes were able to be run.
  36532. */
  36533. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  36534. if (sourceTexture === void 0) { sourceTexture = null; }
  36535. if (postProcesses === void 0) { postProcesses = null; }
  36536. var camera = this._scene.activeCamera;
  36537. if (!camera) {
  36538. return false;
  36539. }
  36540. var postProcesses = postProcesses || camera._postProcesses;
  36541. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36542. return false;
  36543. }
  36544. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  36545. return true;
  36546. };
  36547. /**
  36548. * Manually render a set of post processes to a texture.
  36549. * @param postProcesses An array of post processes to be run.
  36550. * @param targetTexture The target texture to render to.
  36551. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  36552. */
  36553. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  36554. if (targetTexture === void 0) { targetTexture = null; }
  36555. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36556. var engine = this._scene.getEngine();
  36557. for (var index = 0; index < postProcesses.length; index++) {
  36558. if (index < postProcesses.length - 1) {
  36559. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  36560. }
  36561. else {
  36562. if (targetTexture) {
  36563. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  36564. }
  36565. else {
  36566. engine.restoreDefaultFramebuffer();
  36567. }
  36568. }
  36569. var pp = postProcesses[index];
  36570. var effect = pp.apply();
  36571. if (effect) {
  36572. pp.onBeforeRenderObservable.notifyObservers(effect);
  36573. // VBOs
  36574. this._prepareBuffers();
  36575. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36576. // Draw order
  36577. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36578. pp.onAfterRenderObservable.notifyObservers(effect);
  36579. }
  36580. }
  36581. // Restore depth buffer
  36582. engine.setDepthBuffer(true);
  36583. engine.setDepthWrite(true);
  36584. };
  36585. /**
  36586. * Finalize the result of the output of the postprocesses.
  36587. * @param doNotPresent If true the result will not be displayed to the screen.
  36588. * @param targetTexture The target texture to render to.
  36589. * @param faceIndex The index of the face to bind the target texture to.
  36590. * @param postProcesses The array of post processes to render.
  36591. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  36592. */
  36593. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  36594. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36595. var camera = this._scene.activeCamera;
  36596. if (!camera) {
  36597. return;
  36598. }
  36599. postProcesses = postProcesses || camera._postProcesses;
  36600. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36601. return;
  36602. }
  36603. var engine = this._scene.getEngine();
  36604. for (var index = 0, len = postProcesses.length; index < len; index++) {
  36605. if (index < len - 1) {
  36606. postProcesses[index + 1].activate(camera, targetTexture);
  36607. }
  36608. else {
  36609. if (targetTexture) {
  36610. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  36611. }
  36612. else {
  36613. engine.restoreDefaultFramebuffer();
  36614. }
  36615. }
  36616. if (doNotPresent) {
  36617. break;
  36618. }
  36619. var pp = postProcesses[index];
  36620. var effect = pp.apply();
  36621. if (effect) {
  36622. pp.onBeforeRenderObservable.notifyObservers(effect);
  36623. // VBOs
  36624. this._prepareBuffers();
  36625. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36626. // Draw order
  36627. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36628. pp.onAfterRenderObservable.notifyObservers(effect);
  36629. }
  36630. }
  36631. // Restore states
  36632. engine.setDepthBuffer(true);
  36633. engine.setDepthWrite(true);
  36634. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36635. };
  36636. /**
  36637. * Disposes of the post process manager.
  36638. */
  36639. PostProcessManager.prototype.dispose = function () {
  36640. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36641. if (buffer) {
  36642. buffer.dispose();
  36643. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  36644. }
  36645. if (this._indexBuffer) {
  36646. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36647. this._indexBuffer = null;
  36648. }
  36649. };
  36650. return PostProcessManager;
  36651. }());
  36652. BABYLON.PostProcessManager = PostProcessManager;
  36653. })(BABYLON || (BABYLON = {}));
  36654. //# sourceMappingURL=babylon.postProcessManager.js.map
  36655. var BABYLON;
  36656. (function (BABYLON) {
  36657. /**
  36658. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  36659. */
  36660. var PerformanceMonitor = /** @class */ (function () {
  36661. /**
  36662. * constructor
  36663. * @param frameSampleSize The number of samples required to saturate the sliding window
  36664. */
  36665. function PerformanceMonitor(frameSampleSize) {
  36666. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  36667. this._enabled = true;
  36668. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  36669. }
  36670. /**
  36671. * Samples current frame
  36672. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  36673. */
  36674. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  36675. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  36676. if (!this._enabled)
  36677. return;
  36678. if (this._lastFrameTimeMs != null) {
  36679. var dt = timeMs - this._lastFrameTimeMs;
  36680. this._rollingFrameTime.add(dt);
  36681. }
  36682. this._lastFrameTimeMs = timeMs;
  36683. };
  36684. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  36685. /**
  36686. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36687. * @return Average frame time in milliseconds
  36688. */
  36689. get: function () {
  36690. return this._rollingFrameTime.average;
  36691. },
  36692. enumerable: true,
  36693. configurable: true
  36694. });
  36695. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  36696. /**
  36697. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36698. * @return Frame time variance in milliseconds squared
  36699. */
  36700. get: function () {
  36701. return this._rollingFrameTime.variance;
  36702. },
  36703. enumerable: true,
  36704. configurable: true
  36705. });
  36706. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  36707. /**
  36708. * Returns the frame time of the most recent frame
  36709. * @return Frame time in milliseconds
  36710. */
  36711. get: function () {
  36712. return this._rollingFrameTime.history(0);
  36713. },
  36714. enumerable: true,
  36715. configurable: true
  36716. });
  36717. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  36718. /**
  36719. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  36720. * @return Framerate in frames per second
  36721. */
  36722. get: function () {
  36723. return 1000.0 / this._rollingFrameTime.average;
  36724. },
  36725. enumerable: true,
  36726. configurable: true
  36727. });
  36728. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  36729. /**
  36730. * Returns the average framerate in frames per second using the most recent frame time
  36731. * @return Framerate in frames per second
  36732. */
  36733. get: function () {
  36734. var history = this._rollingFrameTime.history(0);
  36735. if (history === 0) {
  36736. return 0;
  36737. }
  36738. return 1000.0 / history;
  36739. },
  36740. enumerable: true,
  36741. configurable: true
  36742. });
  36743. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  36744. /**
  36745. * Returns true if enough samples have been taken to completely fill the sliding window
  36746. * @return true if saturated
  36747. */
  36748. get: function () {
  36749. return this._rollingFrameTime.isSaturated();
  36750. },
  36751. enumerable: true,
  36752. configurable: true
  36753. });
  36754. /**
  36755. * Enables contributions to the sliding window sample set
  36756. */
  36757. PerformanceMonitor.prototype.enable = function () {
  36758. this._enabled = true;
  36759. };
  36760. /**
  36761. * Disables contributions to the sliding window sample set
  36762. * Samples will not be interpolated over the disabled period
  36763. */
  36764. PerformanceMonitor.prototype.disable = function () {
  36765. this._enabled = false;
  36766. //clear last sample to avoid interpolating over the disabled period when next enabled
  36767. this._lastFrameTimeMs = null;
  36768. };
  36769. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  36770. /**
  36771. * Returns true if sampling is enabled
  36772. * @return true if enabled
  36773. */
  36774. get: function () {
  36775. return this._enabled;
  36776. },
  36777. enumerable: true,
  36778. configurable: true
  36779. });
  36780. /**
  36781. * Resets performance monitor
  36782. */
  36783. PerformanceMonitor.prototype.reset = function () {
  36784. //clear last sample to avoid interpolating over the disabled period when next enabled
  36785. this._lastFrameTimeMs = null;
  36786. //wipe record
  36787. this._rollingFrameTime.reset();
  36788. };
  36789. return PerformanceMonitor;
  36790. }());
  36791. BABYLON.PerformanceMonitor = PerformanceMonitor;
  36792. /**
  36793. * RollingAverage
  36794. *
  36795. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  36796. */
  36797. var RollingAverage = /** @class */ (function () {
  36798. /**
  36799. * constructor
  36800. * @param length The number of samples required to saturate the sliding window
  36801. */
  36802. function RollingAverage(length) {
  36803. this._samples = new Array(length);
  36804. this.reset();
  36805. }
  36806. /**
  36807. * Adds a sample to the sample set
  36808. * @param v The sample value
  36809. */
  36810. RollingAverage.prototype.add = function (v) {
  36811. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  36812. var delta;
  36813. //we need to check if we've already wrapped round
  36814. if (this.isSaturated()) {
  36815. //remove bottom of stack from mean
  36816. var bottomValue = this._samples[this._pos];
  36817. delta = bottomValue - this.average;
  36818. this.average -= delta / (this._sampleCount - 1);
  36819. this._m2 -= delta * (bottomValue - this.average);
  36820. }
  36821. else {
  36822. this._sampleCount++;
  36823. }
  36824. //add new value to mean
  36825. delta = v - this.average;
  36826. this.average += delta / (this._sampleCount);
  36827. this._m2 += delta * (v - this.average);
  36828. //set the new variance
  36829. this.variance = this._m2 / (this._sampleCount - 1);
  36830. this._samples[this._pos] = v;
  36831. this._pos++;
  36832. this._pos %= this._samples.length; //positive wrap around
  36833. };
  36834. /**
  36835. * Returns previously added values or null if outside of history or outside the sliding window domain
  36836. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  36837. * @return Value previously recorded with add() or null if outside of range
  36838. */
  36839. RollingAverage.prototype.history = function (i) {
  36840. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  36841. return 0;
  36842. }
  36843. var i0 = this._wrapPosition(this._pos - 1.0);
  36844. return this._samples[this._wrapPosition(i0 - i)];
  36845. };
  36846. /**
  36847. * Returns true if enough samples have been taken to completely fill the sliding window
  36848. * @return true if sample-set saturated
  36849. */
  36850. RollingAverage.prototype.isSaturated = function () {
  36851. return this._sampleCount >= this._samples.length;
  36852. };
  36853. /**
  36854. * Resets the rolling average (equivalent to 0 samples taken so far)
  36855. */
  36856. RollingAverage.prototype.reset = function () {
  36857. this.average = 0;
  36858. this.variance = 0;
  36859. this._sampleCount = 0;
  36860. this._pos = 0;
  36861. this._m2 = 0;
  36862. };
  36863. /**
  36864. * Wraps a value around the sample range boundaries
  36865. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  36866. * @return Wrapped position in sample range
  36867. */
  36868. RollingAverage.prototype._wrapPosition = function (i) {
  36869. var max = this._samples.length;
  36870. return ((i % max) + max) % max;
  36871. };
  36872. return RollingAverage;
  36873. }());
  36874. BABYLON.RollingAverage = RollingAverage;
  36875. })(BABYLON || (BABYLON = {}));
  36876. //# sourceMappingURL=babylon.performanceMonitor.js.map
  36877. var BABYLON;
  36878. (function (BABYLON) {
  36879. /**
  36880. * This groups together the common properties used for image processing either in direct forward pass
  36881. * or through post processing effect depending on the use of the image processing pipeline in your scene
  36882. * or not.
  36883. */
  36884. var ImageProcessingConfiguration = /** @class */ (function () {
  36885. function ImageProcessingConfiguration() {
  36886. /**
  36887. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  36888. */
  36889. this.colorCurves = new BABYLON.ColorCurves();
  36890. this._colorCurvesEnabled = false;
  36891. this._colorGradingEnabled = false;
  36892. this._colorGradingWithGreenDepth = true;
  36893. this._colorGradingBGR = true;
  36894. this._exposure = 1.0;
  36895. this._toneMappingEnabled = false;
  36896. this._contrast = 1.0;
  36897. /**
  36898. * Vignette stretch size.
  36899. */
  36900. this.vignetteStretch = 0;
  36901. /**
  36902. * Vignette centre X Offset.
  36903. */
  36904. this.vignetteCentreX = 0;
  36905. /**
  36906. * Vignette centre Y Offset.
  36907. */
  36908. this.vignetteCentreY = 0;
  36909. /**
  36910. * Vignette weight or intensity of the vignette effect.
  36911. */
  36912. this.vignetteWeight = 1.5;
  36913. /**
  36914. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  36915. * if vignetteEnabled is set to true.
  36916. */
  36917. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  36918. /**
  36919. * Camera field of view used by the Vignette effect.
  36920. */
  36921. this.vignetteCameraFov = 0.5;
  36922. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  36923. this._vignetteEnabled = false;
  36924. this._applyByPostProcess = false;
  36925. this._isEnabled = true;
  36926. /**
  36927. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  36928. * @type {BABYLON.Observable}
  36929. */
  36930. this.onUpdateParameters = new BABYLON.Observable();
  36931. }
  36932. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  36933. /**
  36934. * Gets wether the color curves effect is enabled.
  36935. */
  36936. get: function () {
  36937. return this._colorCurvesEnabled;
  36938. },
  36939. /**
  36940. * Sets wether the color curves effect is enabled.
  36941. */
  36942. set: function (value) {
  36943. if (this._colorCurvesEnabled === value) {
  36944. return;
  36945. }
  36946. this._colorCurvesEnabled = value;
  36947. this._updateParameters();
  36948. },
  36949. enumerable: true,
  36950. configurable: true
  36951. });
  36952. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  36953. /**
  36954. * Gets wether the color grading effect is enabled.
  36955. */
  36956. get: function () {
  36957. return this._colorGradingEnabled;
  36958. },
  36959. /**
  36960. * Sets wether the color grading effect is enabled.
  36961. */
  36962. set: function (value) {
  36963. if (this._colorGradingEnabled === value) {
  36964. return;
  36965. }
  36966. this._colorGradingEnabled = value;
  36967. this._updateParameters();
  36968. },
  36969. enumerable: true,
  36970. configurable: true
  36971. });
  36972. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  36973. /**
  36974. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  36975. */
  36976. get: function () {
  36977. return this._colorGradingWithGreenDepth;
  36978. },
  36979. /**
  36980. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  36981. */
  36982. set: function (value) {
  36983. if (this._colorGradingWithGreenDepth === value) {
  36984. return;
  36985. }
  36986. this._colorGradingWithGreenDepth = value;
  36987. this._updateParameters();
  36988. },
  36989. enumerable: true,
  36990. configurable: true
  36991. });
  36992. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  36993. /**
  36994. * Gets wether the color grading texture contains BGR values.
  36995. */
  36996. get: function () {
  36997. return this._colorGradingBGR;
  36998. },
  36999. /**
  37000. * Sets wether the color grading texture contains BGR values.
  37001. */
  37002. set: function (value) {
  37003. if (this._colorGradingBGR === value) {
  37004. return;
  37005. }
  37006. this._colorGradingBGR = value;
  37007. this._updateParameters();
  37008. },
  37009. enumerable: true,
  37010. configurable: true
  37011. });
  37012. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  37013. /**
  37014. * Gets the Exposure used in the effect.
  37015. */
  37016. get: function () {
  37017. return this._exposure;
  37018. },
  37019. /**
  37020. * Sets the Exposure used in the effect.
  37021. */
  37022. set: function (value) {
  37023. if (this._exposure === value) {
  37024. return;
  37025. }
  37026. this._exposure = value;
  37027. this._updateParameters();
  37028. },
  37029. enumerable: true,
  37030. configurable: true
  37031. });
  37032. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  37033. /**
  37034. * Gets wether the tone mapping effect is enabled.
  37035. */
  37036. get: function () {
  37037. return this._toneMappingEnabled;
  37038. },
  37039. /**
  37040. * Sets wether the tone mapping effect is enabled.
  37041. */
  37042. set: function (value) {
  37043. if (this._toneMappingEnabled === value) {
  37044. return;
  37045. }
  37046. this._toneMappingEnabled = value;
  37047. this._updateParameters();
  37048. },
  37049. enumerable: true,
  37050. configurable: true
  37051. });
  37052. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  37053. /**
  37054. * Gets the contrast used in the effect.
  37055. */
  37056. get: function () {
  37057. return this._contrast;
  37058. },
  37059. /**
  37060. * Sets the contrast used in the effect.
  37061. */
  37062. set: function (value) {
  37063. if (this._contrast === value) {
  37064. return;
  37065. }
  37066. this._contrast = value;
  37067. this._updateParameters();
  37068. },
  37069. enumerable: true,
  37070. configurable: true
  37071. });
  37072. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37073. /**
  37074. * Gets the vignette blend mode allowing different kind of effect.
  37075. */
  37076. get: function () {
  37077. return this._vignetteBlendMode;
  37078. },
  37079. /**
  37080. * Sets the vignette blend mode allowing different kind of effect.
  37081. */
  37082. set: function (value) {
  37083. if (this._vignetteBlendMode === value) {
  37084. return;
  37085. }
  37086. this._vignetteBlendMode = value;
  37087. this._updateParameters();
  37088. },
  37089. enumerable: true,
  37090. configurable: true
  37091. });
  37092. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37093. /**
  37094. * Gets wether the vignette effect is enabled.
  37095. */
  37096. get: function () {
  37097. return this._vignetteEnabled;
  37098. },
  37099. /**
  37100. * Sets wether the vignette effect is enabled.
  37101. */
  37102. set: function (value) {
  37103. if (this._vignetteEnabled === value) {
  37104. return;
  37105. }
  37106. this._vignetteEnabled = value;
  37107. this._updateParameters();
  37108. },
  37109. enumerable: true,
  37110. configurable: true
  37111. });
  37112. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37113. /**
  37114. * Gets wether the image processing is applied through a post process or not.
  37115. */
  37116. get: function () {
  37117. return this._applyByPostProcess;
  37118. },
  37119. /**
  37120. * Sets wether the image processing is applied through a post process or not.
  37121. */
  37122. set: function (value) {
  37123. if (this._applyByPostProcess === value) {
  37124. return;
  37125. }
  37126. this._applyByPostProcess = value;
  37127. this._updateParameters();
  37128. },
  37129. enumerable: true,
  37130. configurable: true
  37131. });
  37132. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37133. /**
  37134. * Gets wether the image processing is enabled or not.
  37135. */
  37136. get: function () {
  37137. return this._isEnabled;
  37138. },
  37139. /**
  37140. * Sets wether the image processing is enabled or not.
  37141. */
  37142. set: function (value) {
  37143. if (this._isEnabled === value) {
  37144. return;
  37145. }
  37146. this._isEnabled = value;
  37147. this._updateParameters();
  37148. },
  37149. enumerable: true,
  37150. configurable: true
  37151. });
  37152. /**
  37153. * Method called each time the image processing information changes requires to recompile the effect.
  37154. */
  37155. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37156. this.onUpdateParameters.notifyObservers(this);
  37157. };
  37158. ImageProcessingConfiguration.prototype.getClassName = function () {
  37159. return "ImageProcessingConfiguration";
  37160. };
  37161. /**
  37162. * Prepare the list of uniforms associated with the Image Processing effects.
  37163. * @param uniformsList The list of uniforms used in the effect
  37164. * @param defines the list of defines currently in use
  37165. */
  37166. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37167. if (defines.EXPOSURE) {
  37168. uniforms.push("exposureLinear");
  37169. }
  37170. if (defines.CONTRAST) {
  37171. uniforms.push("contrast");
  37172. }
  37173. if (defines.COLORGRADING) {
  37174. uniforms.push("colorTransformSettings");
  37175. }
  37176. if (defines.VIGNETTE) {
  37177. uniforms.push("vInverseScreenSize");
  37178. uniforms.push("vignetteSettings1");
  37179. uniforms.push("vignetteSettings2");
  37180. }
  37181. if (defines.COLORCURVES) {
  37182. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37183. }
  37184. };
  37185. /**
  37186. * Prepare the list of samplers associated with the Image Processing effects.
  37187. * @param uniformsList The list of uniforms used in the effect
  37188. * @param defines the list of defines currently in use
  37189. */
  37190. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37191. if (defines.COLORGRADING) {
  37192. samplersList.push("txColorTransform");
  37193. }
  37194. };
  37195. /**
  37196. * Prepare the list of defines associated to the shader.
  37197. * @param defines the list of defines to complete
  37198. */
  37199. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37200. if (forPostProcess === void 0) { forPostProcess = false; }
  37201. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37202. defines.VIGNETTE = false;
  37203. defines.TONEMAPPING = false;
  37204. defines.CONTRAST = false;
  37205. defines.EXPOSURE = false;
  37206. defines.COLORCURVES = false;
  37207. defines.COLORGRADING = false;
  37208. defines.COLORGRADING3D = false;
  37209. defines.IMAGEPROCESSING = false;
  37210. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37211. return;
  37212. }
  37213. defines.VIGNETTE = this.vignetteEnabled;
  37214. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37215. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37216. defines.TONEMAPPING = this.toneMappingEnabled;
  37217. defines.CONTRAST = (this.contrast !== 1.0);
  37218. defines.EXPOSURE = (this.exposure !== 1.0);
  37219. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37220. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37221. if (defines.COLORGRADING) {
  37222. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37223. }
  37224. else {
  37225. defines.COLORGRADING3D = false;
  37226. }
  37227. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37228. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37229. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37230. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  37231. };
  37232. /**
  37233. * Returns true if all the image processing information are ready.
  37234. */
  37235. ImageProcessingConfiguration.prototype.isReady = function () {
  37236. // Color Grading texure can not be none blocking.
  37237. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37238. };
  37239. /**
  37240. * Binds the image processing to the shader.
  37241. * @param effect The effect to bind to
  37242. */
  37243. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37244. if (aspectRatio === void 0) { aspectRatio = 1; }
  37245. // Color Curves
  37246. if (this._colorCurvesEnabled && this.colorCurves) {
  37247. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37248. }
  37249. // Vignette
  37250. if (this._vignetteEnabled) {
  37251. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37252. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37253. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37254. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37255. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37256. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37257. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37258. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37259. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37260. var vignettePower = -2.0 * this.vignetteWeight;
  37261. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37262. }
  37263. // Exposure
  37264. effect.setFloat("exposureLinear", this.exposure);
  37265. // Contrast
  37266. effect.setFloat("contrast", this.contrast);
  37267. // Color transform settings
  37268. if (this.colorGradingTexture) {
  37269. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37270. var textureSize = this.colorGradingTexture.getSize().height;
  37271. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37272. 0.5 / textureSize, // textureOffset
  37273. textureSize, // textureSize
  37274. this.colorGradingTexture.level // weight
  37275. );
  37276. }
  37277. };
  37278. /**
  37279. * Clones the current image processing instance.
  37280. * @return The cloned image processing
  37281. */
  37282. ImageProcessingConfiguration.prototype.clone = function () {
  37283. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37284. };
  37285. /**
  37286. * Serializes the current image processing instance to a json representation.
  37287. * @return a JSON representation
  37288. */
  37289. ImageProcessingConfiguration.prototype.serialize = function () {
  37290. return BABYLON.SerializationHelper.Serialize(this);
  37291. };
  37292. /**
  37293. * Parses the image processing from a json representation.
  37294. * @param source the JSON source to parse
  37295. * @return The parsed image processing
  37296. */
  37297. ImageProcessingConfiguration.Parse = function (source) {
  37298. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  37299. };
  37300. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  37301. /**
  37302. * Used to apply the vignette as a mix with the pixel color.
  37303. */
  37304. get: function () {
  37305. return this._VIGNETTEMODE_MULTIPLY;
  37306. },
  37307. enumerable: true,
  37308. configurable: true
  37309. });
  37310. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  37311. /**
  37312. * Used to apply the vignette as a replacement of the pixel color.
  37313. */
  37314. get: function () {
  37315. return this._VIGNETTEMODE_OPAQUE;
  37316. },
  37317. enumerable: true,
  37318. configurable: true
  37319. });
  37320. // Static constants associated to the image processing.
  37321. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  37322. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  37323. __decorate([
  37324. BABYLON.serializeAsColorCurves()
  37325. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  37326. __decorate([
  37327. BABYLON.serialize()
  37328. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  37329. __decorate([
  37330. BABYLON.serializeAsTexture()
  37331. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  37332. __decorate([
  37333. BABYLON.serialize()
  37334. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  37335. __decorate([
  37336. BABYLON.serialize()
  37337. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  37338. __decorate([
  37339. BABYLON.serialize()
  37340. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  37341. __decorate([
  37342. BABYLON.serialize()
  37343. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  37344. __decorate([
  37345. BABYLON.serialize()
  37346. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  37347. __decorate([
  37348. BABYLON.serialize()
  37349. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  37350. __decorate([
  37351. BABYLON.serialize()
  37352. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  37353. __decorate([
  37354. BABYLON.serialize()
  37355. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  37356. __decorate([
  37357. BABYLON.serialize()
  37358. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  37359. __decorate([
  37360. BABYLON.serialize()
  37361. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  37362. __decorate([
  37363. BABYLON.serializeAsColor4()
  37364. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  37365. __decorate([
  37366. BABYLON.serialize()
  37367. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  37368. __decorate([
  37369. BABYLON.serialize()
  37370. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  37371. __decorate([
  37372. BABYLON.serialize()
  37373. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  37374. __decorate([
  37375. BABYLON.serialize()
  37376. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  37377. __decorate([
  37378. BABYLON.serialize()
  37379. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  37380. return ImageProcessingConfiguration;
  37381. }());
  37382. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  37383. })(BABYLON || (BABYLON = {}));
  37384. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  37385. var BABYLON;
  37386. (function (BABYLON) {
  37387. /**
  37388. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  37389. * It can help converting any input color in a desired output one. This can then be used to create effects
  37390. * from sepia, black and white to sixties or futuristic rendering...
  37391. *
  37392. * The only supported format is currently 3dl.
  37393. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  37394. */
  37395. var ColorGradingTexture = /** @class */ (function (_super) {
  37396. __extends(ColorGradingTexture, _super);
  37397. /**
  37398. * Instantiates a ColorGradingTexture from the following parameters.
  37399. *
  37400. * @param url The location of the color gradind data (currently only supporting 3dl)
  37401. * @param scene The scene the texture will be used in
  37402. */
  37403. function ColorGradingTexture(url, scene) {
  37404. var _this = _super.call(this, scene) || this;
  37405. if (!url) {
  37406. return _this;
  37407. }
  37408. _this._engine = scene.getEngine();
  37409. _this._textureMatrix = BABYLON.Matrix.Identity();
  37410. _this.name = url;
  37411. _this.url = url;
  37412. _this.hasAlpha = false;
  37413. _this.isCube = false;
  37414. _this.is3D = _this._engine.webGLVersion > 1;
  37415. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37416. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37417. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37418. _this.anisotropicFilteringLevel = 1;
  37419. _this._texture = _this._getFromCache(url, true);
  37420. if (!_this._texture) {
  37421. if (!scene.useDelayedTextureLoading) {
  37422. _this.loadTexture();
  37423. }
  37424. else {
  37425. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  37426. }
  37427. }
  37428. return _this;
  37429. }
  37430. /**
  37431. * Returns the texture matrix used in most of the material.
  37432. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  37433. */
  37434. ColorGradingTexture.prototype.getTextureMatrix = function () {
  37435. return this._textureMatrix;
  37436. };
  37437. /**
  37438. * Occurs when the file being loaded is a .3dl LUT file.
  37439. */
  37440. ColorGradingTexture.prototype.load3dlTexture = function () {
  37441. var engine = this._engine;
  37442. var texture;
  37443. if (engine.webGLVersion === 1) {
  37444. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37445. }
  37446. else {
  37447. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37448. }
  37449. this._texture = texture;
  37450. var callback = function (text) {
  37451. if (typeof text !== "string") {
  37452. return;
  37453. }
  37454. var data = null;
  37455. var tempData = null;
  37456. var line;
  37457. var lines = text.split('\n');
  37458. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  37459. var maxColor = 0;
  37460. for (var i = 0; i < lines.length; i++) {
  37461. line = lines[i];
  37462. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  37463. continue;
  37464. if (line.indexOf('#') === 0)
  37465. continue;
  37466. var words = line.split(" ");
  37467. if (size === 0) {
  37468. // Number of space + one
  37469. size = words.length;
  37470. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  37471. tempData = new Float32Array(size * size * size * 4);
  37472. continue;
  37473. }
  37474. if (size != 0) {
  37475. var r = Math.max(parseInt(words[0]), 0);
  37476. var g = Math.max(parseInt(words[1]), 0);
  37477. var b = Math.max(parseInt(words[2]), 0);
  37478. maxColor = Math.max(r, maxColor);
  37479. maxColor = Math.max(g, maxColor);
  37480. maxColor = Math.max(b, maxColor);
  37481. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  37482. if (tempData) {
  37483. tempData[pixelStorageIndex + 0] = r;
  37484. tempData[pixelStorageIndex + 1] = g;
  37485. tempData[pixelStorageIndex + 2] = b;
  37486. }
  37487. pixelIndexSlice++;
  37488. if (pixelIndexSlice % size == 0) {
  37489. pixelIndexH++;
  37490. pixelIndexSlice = 0;
  37491. if (pixelIndexH % size == 0) {
  37492. pixelIndexW++;
  37493. pixelIndexH = 0;
  37494. }
  37495. }
  37496. }
  37497. }
  37498. if (tempData && data) {
  37499. for (var i = 0; i < tempData.length; i++) {
  37500. if (i > 0 && (i + 1) % 4 === 0) {
  37501. data[i] = 255;
  37502. }
  37503. else {
  37504. var value = tempData[i];
  37505. data[i] = (value / maxColor * 255);
  37506. }
  37507. }
  37508. }
  37509. if (texture.is3D) {
  37510. texture.updateSize(size, size, size);
  37511. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37512. }
  37513. else {
  37514. texture.updateSize(size * size, size);
  37515. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37516. }
  37517. };
  37518. var scene = this.getScene();
  37519. if (scene) {
  37520. scene._loadFile(this.url, callback);
  37521. }
  37522. else {
  37523. this._engine._loadFile(this.url, callback);
  37524. }
  37525. return this._texture;
  37526. };
  37527. /**
  37528. * Starts the loading process of the texture.
  37529. */
  37530. ColorGradingTexture.prototype.loadTexture = function () {
  37531. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  37532. this.load3dlTexture();
  37533. }
  37534. };
  37535. /**
  37536. * Clones the color gradind texture.
  37537. */
  37538. ColorGradingTexture.prototype.clone = function () {
  37539. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  37540. // Base texture
  37541. newTexture.level = this.level;
  37542. return newTexture;
  37543. };
  37544. /**
  37545. * Called during delayed load for textures.
  37546. */
  37547. ColorGradingTexture.prototype.delayLoad = function () {
  37548. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  37549. return;
  37550. }
  37551. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  37552. this._texture = this._getFromCache(this.url, true);
  37553. if (!this._texture) {
  37554. this.loadTexture();
  37555. }
  37556. };
  37557. /**
  37558. * Parses a color grading texture serialized by Babylon.
  37559. * @param parsedTexture The texture information being parsedTexture
  37560. * @param scene The scene to load the texture in
  37561. * @param rootUrl The root url of the data assets to load
  37562. * @return A color gradind texture
  37563. */
  37564. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  37565. var texture = null;
  37566. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  37567. texture = new ColorGradingTexture(parsedTexture.name, scene);
  37568. texture.name = parsedTexture.name;
  37569. texture.level = parsedTexture.level;
  37570. }
  37571. return texture;
  37572. };
  37573. /**
  37574. * Serializes the LUT texture to json format.
  37575. */
  37576. ColorGradingTexture.prototype.serialize = function () {
  37577. if (!this.name) {
  37578. return null;
  37579. }
  37580. var serializationObject = {};
  37581. serializationObject.name = this.name;
  37582. serializationObject.level = this.level;
  37583. serializationObject.customType = "BABYLON.ColorGradingTexture";
  37584. return serializationObject;
  37585. };
  37586. /**
  37587. * Empty line regex stored for GC.
  37588. */
  37589. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  37590. return ColorGradingTexture;
  37591. }(BABYLON.BaseTexture));
  37592. BABYLON.ColorGradingTexture = ColorGradingTexture;
  37593. })(BABYLON || (BABYLON = {}));
  37594. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  37595. var BABYLON;
  37596. (function (BABYLON) {
  37597. /**
  37598. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37599. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37600. * 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;
  37601. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37602. */
  37603. var ColorCurves = /** @class */ (function () {
  37604. function ColorCurves() {
  37605. this._dirty = true;
  37606. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  37607. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  37608. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37609. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  37610. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37611. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  37612. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  37613. this._globalHue = 30;
  37614. this._globalDensity = 0;
  37615. this._globalSaturation = 0;
  37616. this._globalExposure = 0;
  37617. this._highlightsHue = 30;
  37618. this._highlightsDensity = 0;
  37619. this._highlightsSaturation = 0;
  37620. this._highlightsExposure = 0;
  37621. this._midtonesHue = 30;
  37622. this._midtonesDensity = 0;
  37623. this._midtonesSaturation = 0;
  37624. this._midtonesExposure = 0;
  37625. this._shadowsHue = 30;
  37626. this._shadowsDensity = 0;
  37627. this._shadowsSaturation = 0;
  37628. this._shadowsExposure = 0;
  37629. }
  37630. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  37631. /**
  37632. * Gets the global Hue value.
  37633. * 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).
  37634. */
  37635. get: function () {
  37636. return this._globalHue;
  37637. },
  37638. /**
  37639. * Sets the global Hue value.
  37640. * 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).
  37641. */
  37642. set: function (value) {
  37643. this._globalHue = value;
  37644. this._dirty = true;
  37645. },
  37646. enumerable: true,
  37647. configurable: true
  37648. });
  37649. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  37650. /**
  37651. * Gets the global Density value.
  37652. * 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.
  37653. * Values less than zero provide a filter of opposite hue.
  37654. */
  37655. get: function () {
  37656. return this._globalDensity;
  37657. },
  37658. /**
  37659. * Sets the global Density value.
  37660. * 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.
  37661. * Values less than zero provide a filter of opposite hue.
  37662. */
  37663. set: function (value) {
  37664. this._globalDensity = value;
  37665. this._dirty = true;
  37666. },
  37667. enumerable: true,
  37668. configurable: true
  37669. });
  37670. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  37671. /**
  37672. * Gets the global Saturation value.
  37673. * 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.
  37674. */
  37675. get: function () {
  37676. return this._globalSaturation;
  37677. },
  37678. /**
  37679. * Sets the global Saturation value.
  37680. * 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.
  37681. */
  37682. set: function (value) {
  37683. this._globalSaturation = value;
  37684. this._dirty = true;
  37685. },
  37686. enumerable: true,
  37687. configurable: true
  37688. });
  37689. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  37690. /**
  37691. * Gets the highlights Hue value.
  37692. * 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).
  37693. */
  37694. get: function () {
  37695. return this._highlightsHue;
  37696. },
  37697. /**
  37698. * Sets the highlights Hue value.
  37699. * 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).
  37700. */
  37701. set: function (value) {
  37702. this._highlightsHue = value;
  37703. this._dirty = true;
  37704. },
  37705. enumerable: true,
  37706. configurable: true
  37707. });
  37708. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  37709. /**
  37710. * Gets the highlights Density value.
  37711. * 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.
  37712. * Values less than zero provide a filter of opposite hue.
  37713. */
  37714. get: function () {
  37715. return this._highlightsDensity;
  37716. },
  37717. /**
  37718. * Sets the highlights Density value.
  37719. * 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.
  37720. * Values less than zero provide a filter of opposite hue.
  37721. */
  37722. set: function (value) {
  37723. this._highlightsDensity = value;
  37724. this._dirty = true;
  37725. },
  37726. enumerable: true,
  37727. configurable: true
  37728. });
  37729. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  37730. /**
  37731. * Gets the highlights Saturation value.
  37732. * 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.
  37733. */
  37734. get: function () {
  37735. return this._highlightsSaturation;
  37736. },
  37737. /**
  37738. * Sets the highlights Saturation value.
  37739. * 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.
  37740. */
  37741. set: function (value) {
  37742. this._highlightsSaturation = value;
  37743. this._dirty = true;
  37744. },
  37745. enumerable: true,
  37746. configurable: true
  37747. });
  37748. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  37749. /**
  37750. * Gets the highlights Exposure value.
  37751. * 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.
  37752. */
  37753. get: function () {
  37754. return this._highlightsExposure;
  37755. },
  37756. /**
  37757. * Sets the highlights Exposure value.
  37758. * 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.
  37759. */
  37760. set: function (value) {
  37761. this._highlightsExposure = value;
  37762. this._dirty = true;
  37763. },
  37764. enumerable: true,
  37765. configurable: true
  37766. });
  37767. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  37768. /**
  37769. * Gets the midtones Hue value.
  37770. * 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).
  37771. */
  37772. get: function () {
  37773. return this._midtonesHue;
  37774. },
  37775. /**
  37776. * Sets the midtones Hue value.
  37777. * 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).
  37778. */
  37779. set: function (value) {
  37780. this._midtonesHue = value;
  37781. this._dirty = true;
  37782. },
  37783. enumerable: true,
  37784. configurable: true
  37785. });
  37786. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  37787. /**
  37788. * Gets the midtones Density value.
  37789. * 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.
  37790. * Values less than zero provide a filter of opposite hue.
  37791. */
  37792. get: function () {
  37793. return this._midtonesDensity;
  37794. },
  37795. /**
  37796. * Sets the midtones Density value.
  37797. * 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.
  37798. * Values less than zero provide a filter of opposite hue.
  37799. */
  37800. set: function (value) {
  37801. this._midtonesDensity = value;
  37802. this._dirty = true;
  37803. },
  37804. enumerable: true,
  37805. configurable: true
  37806. });
  37807. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  37808. /**
  37809. * Gets the midtones Saturation value.
  37810. * 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.
  37811. */
  37812. get: function () {
  37813. return this._midtonesSaturation;
  37814. },
  37815. /**
  37816. * Sets the midtones Saturation value.
  37817. * 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.
  37818. */
  37819. set: function (value) {
  37820. this._midtonesSaturation = value;
  37821. this._dirty = true;
  37822. },
  37823. enumerable: true,
  37824. configurable: true
  37825. });
  37826. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  37827. /**
  37828. * Gets the midtones Exposure value.
  37829. * 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.
  37830. */
  37831. get: function () {
  37832. return this._midtonesExposure;
  37833. },
  37834. /**
  37835. * Sets the midtones Exposure value.
  37836. * 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.
  37837. */
  37838. set: function (value) {
  37839. this._midtonesExposure = value;
  37840. this._dirty = true;
  37841. },
  37842. enumerable: true,
  37843. configurable: true
  37844. });
  37845. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  37846. /**
  37847. * Gets the shadows Hue value.
  37848. * 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).
  37849. */
  37850. get: function () {
  37851. return this._shadowsHue;
  37852. },
  37853. /**
  37854. * Sets the shadows Hue value.
  37855. * 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).
  37856. */
  37857. set: function (value) {
  37858. this._shadowsHue = value;
  37859. this._dirty = true;
  37860. },
  37861. enumerable: true,
  37862. configurable: true
  37863. });
  37864. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  37865. /**
  37866. * Gets the shadows Density value.
  37867. * 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.
  37868. * Values less than zero provide a filter of opposite hue.
  37869. */
  37870. get: function () {
  37871. return this._shadowsDensity;
  37872. },
  37873. /**
  37874. * Sets the shadows Density value.
  37875. * 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.
  37876. * Values less than zero provide a filter of opposite hue.
  37877. */
  37878. set: function (value) {
  37879. this._shadowsDensity = value;
  37880. this._dirty = true;
  37881. },
  37882. enumerable: true,
  37883. configurable: true
  37884. });
  37885. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  37886. /**
  37887. * Gets the shadows Saturation value.
  37888. * 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.
  37889. */
  37890. get: function () {
  37891. return this._shadowsSaturation;
  37892. },
  37893. /**
  37894. * Sets the shadows Saturation value.
  37895. * 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.
  37896. */
  37897. set: function (value) {
  37898. this._shadowsSaturation = value;
  37899. this._dirty = true;
  37900. },
  37901. enumerable: true,
  37902. configurable: true
  37903. });
  37904. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  37905. /**
  37906. * Gets the shadows Exposure value.
  37907. * 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.
  37908. */
  37909. get: function () {
  37910. return this._shadowsExposure;
  37911. },
  37912. /**
  37913. * Sets the shadows Exposure value.
  37914. * 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.
  37915. */
  37916. set: function (value) {
  37917. this._shadowsExposure = value;
  37918. this._dirty = true;
  37919. },
  37920. enumerable: true,
  37921. configurable: true
  37922. });
  37923. ColorCurves.prototype.getClassName = function () {
  37924. return "ColorCurves";
  37925. };
  37926. /**
  37927. * Binds the color curves to the shader.
  37928. * @param colorCurves The color curve to bind
  37929. * @param effect The effect to bind to
  37930. */
  37931. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  37932. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  37933. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  37934. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  37935. if (colorCurves._dirty) {
  37936. colorCurves._dirty = false;
  37937. // Fill in global info.
  37938. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  37939. // Compute highlights info.
  37940. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  37941. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  37942. // Compute midtones info.
  37943. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  37944. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  37945. // Compute shadows info.
  37946. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  37947. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  37948. // Compute deltas (neutral is midtones).
  37949. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  37950. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  37951. }
  37952. if (effect) {
  37953. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  37954. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  37955. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  37956. }
  37957. };
  37958. /**
  37959. * Prepare the list of uniforms associated with the ColorCurves effects.
  37960. * @param uniformsList The list of uniforms used in the effect
  37961. */
  37962. ColorCurves.PrepareUniforms = function (uniformsList) {
  37963. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  37964. };
  37965. /**
  37966. * Returns color grading data based on a hue, density, saturation and exposure value.
  37967. * @param filterHue The hue of the color filter.
  37968. * @param filterDensity The density of the color filter.
  37969. * @param saturation The saturation.
  37970. * @param exposure The exposure.
  37971. * @param result The result data container.
  37972. */
  37973. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  37974. if (hue == null) {
  37975. return;
  37976. }
  37977. hue = ColorCurves.clamp(hue, 0, 360);
  37978. density = ColorCurves.clamp(density, -100, 100);
  37979. saturation = ColorCurves.clamp(saturation, -100, 100);
  37980. exposure = ColorCurves.clamp(exposure, -100, 100);
  37981. // Remap the slider/config filter density with non-linear mapping and also scale by half
  37982. // so that the maximum filter density is only 50% control. This provides fine control
  37983. // for small values and reasonable range.
  37984. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  37985. density *= 0.5;
  37986. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  37987. if (density < 0) {
  37988. density *= -1;
  37989. hue = (hue + 180) % 360;
  37990. }
  37991. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  37992. result.scaleToRef(2, result);
  37993. result.a = 1 + 0.01 * saturation;
  37994. };
  37995. /**
  37996. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  37997. * @param value The input slider value in range [-100,100].
  37998. * @returns Adjusted value.
  37999. */
  38000. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  38001. value /= 100;
  38002. var x = Math.abs(value);
  38003. x = Math.pow(x, 2);
  38004. if (value < 0) {
  38005. x *= -1;
  38006. }
  38007. x *= 100;
  38008. return x;
  38009. };
  38010. /**
  38011. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  38012. * @param hue The hue (H) input.
  38013. * @param saturation The saturation (S) input.
  38014. * @param brightness The brightness (B) input.
  38015. * @result An RGBA color represented as Vector4.
  38016. */
  38017. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  38018. var h = ColorCurves.clamp(hue, 0, 360);
  38019. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  38020. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  38021. if (s === 0) {
  38022. result.r = v;
  38023. result.g = v;
  38024. result.b = v;
  38025. }
  38026. else {
  38027. // sector 0 to 5
  38028. h /= 60;
  38029. var i = Math.floor(h);
  38030. // fractional part of h
  38031. var f = h - i;
  38032. var p = v * (1 - s);
  38033. var q = v * (1 - s * f);
  38034. var t = v * (1 - s * (1 - f));
  38035. switch (i) {
  38036. case 0:
  38037. result.r = v;
  38038. result.g = t;
  38039. result.b = p;
  38040. break;
  38041. case 1:
  38042. result.r = q;
  38043. result.g = v;
  38044. result.b = p;
  38045. break;
  38046. case 2:
  38047. result.r = p;
  38048. result.g = v;
  38049. result.b = t;
  38050. break;
  38051. case 3:
  38052. result.r = p;
  38053. result.g = q;
  38054. result.b = v;
  38055. break;
  38056. case 4:
  38057. result.r = t;
  38058. result.g = p;
  38059. result.b = v;
  38060. break;
  38061. default:// case 5:
  38062. result.r = v;
  38063. result.g = p;
  38064. result.b = q;
  38065. break;
  38066. }
  38067. }
  38068. result.a = 1;
  38069. };
  38070. /**
  38071. * Returns a value clamped between min and max
  38072. * @param value The value to clamp
  38073. * @param min The minimum of value
  38074. * @param max The maximum of value
  38075. * @returns The clamped value.
  38076. */
  38077. ColorCurves.clamp = function (value, min, max) {
  38078. return Math.min(Math.max(value, min), max);
  38079. };
  38080. /**
  38081. * Clones the current color curve instance.
  38082. * @return The cloned curves
  38083. */
  38084. ColorCurves.prototype.clone = function () {
  38085. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38086. };
  38087. /**
  38088. * Serializes the current color curve instance to a json representation.
  38089. * @return a JSON representation
  38090. */
  38091. ColorCurves.prototype.serialize = function () {
  38092. return BABYLON.SerializationHelper.Serialize(this);
  38093. };
  38094. /**
  38095. * Parses the color curve from a json representation.
  38096. * @param source the JSON source to parse
  38097. * @return The parsed curves
  38098. */
  38099. ColorCurves.Parse = function (source) {
  38100. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38101. };
  38102. __decorate([
  38103. BABYLON.serialize()
  38104. ], ColorCurves.prototype, "_globalHue", void 0);
  38105. __decorate([
  38106. BABYLON.serialize()
  38107. ], ColorCurves.prototype, "_globalDensity", void 0);
  38108. __decorate([
  38109. BABYLON.serialize()
  38110. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38111. __decorate([
  38112. BABYLON.serialize()
  38113. ], ColorCurves.prototype, "_globalExposure", void 0);
  38114. __decorate([
  38115. BABYLON.serialize()
  38116. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38117. __decorate([
  38118. BABYLON.serialize()
  38119. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38120. __decorate([
  38121. BABYLON.serialize()
  38122. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38123. __decorate([
  38124. BABYLON.serialize()
  38125. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38126. __decorate([
  38127. BABYLON.serialize()
  38128. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38129. __decorate([
  38130. BABYLON.serialize()
  38131. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38132. __decorate([
  38133. BABYLON.serialize()
  38134. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38135. __decorate([
  38136. BABYLON.serialize()
  38137. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38138. return ColorCurves;
  38139. }());
  38140. BABYLON.ColorCurves = ColorCurves;
  38141. })(BABYLON || (BABYLON = {}));
  38142. //# sourceMappingURL=babylon.colorCurves.js.map
  38143. //# sourceMappingURL=babylon.behavior.js.map
  38144. var BABYLON;
  38145. (function (BABYLON) {
  38146. /**
  38147. * "Static Class" containing the most commonly used helper while dealing with material for
  38148. * rendering purpose.
  38149. *
  38150. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38151. *
  38152. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38153. */
  38154. var MaterialHelper = /** @class */ (function () {
  38155. function MaterialHelper() {
  38156. }
  38157. /**
  38158. * Bind the current view position to an effect.
  38159. * @param effect The effect to be bound
  38160. * @param scene The scene the eyes position is used from
  38161. */
  38162. MaterialHelper.BindEyePosition = function (effect, scene) {
  38163. if (scene._forcedViewPosition) {
  38164. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38165. return;
  38166. }
  38167. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38168. };
  38169. /**
  38170. * Helps preparing the defines values about the UVs in used in the effect.
  38171. * UVs are shared as much as we can accross chanels in the shaders.
  38172. * @param texture The texture we are preparing the UVs for
  38173. * @param defines The defines to update
  38174. * @param key The chanel key "diffuse", "specular"... used in the shader
  38175. */
  38176. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38177. defines._needUVs = true;
  38178. defines[key] = true;
  38179. if (texture.getTextureMatrix().isIdentity(true)) {
  38180. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38181. if (texture.coordinatesIndex === 0) {
  38182. defines["MAINUV1"] = true;
  38183. }
  38184. else {
  38185. defines["MAINUV2"] = true;
  38186. }
  38187. }
  38188. else {
  38189. defines[key + "DIRECTUV"] = 0;
  38190. }
  38191. };
  38192. /**
  38193. * Binds a texture matrix value to its corrsponding uniform
  38194. * @param texture The texture to bind the matrix for
  38195. * @param uniformBuffer The uniform buffer receivin the data
  38196. * @param key The chanel key "diffuse", "specular"... used in the shader
  38197. */
  38198. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38199. var matrix = texture.getTextureMatrix();
  38200. if (!matrix.isIdentity(true)) {
  38201. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38202. }
  38203. };
  38204. /**
  38205. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38206. * @param mesh defines the current mesh
  38207. * @param scene defines the current scene
  38208. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38209. * @param pointsCloud defines if point cloud rendering has to be turned on
  38210. * @param fogEnabled defines if fog has to be turned on
  38211. * @param alphaTest defines if alpha testing has to be turned on
  38212. * @param defines defines the current list of defines
  38213. */
  38214. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38215. if (defines._areMiscDirty) {
  38216. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38217. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  38218. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38219. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38220. defines["ALPHATEST"] = alphaTest;
  38221. }
  38222. };
  38223. /**
  38224. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38225. * @param scene defines the current scene
  38226. * @param engine defines the current engine
  38227. * @param defines specifies the list of active defines
  38228. * @param useInstances defines if instances have to be turned on
  38229. * @param useClipPlane defines if clip plane have to be turned on
  38230. */
  38231. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38232. if (useClipPlane === void 0) { useClipPlane = null; }
  38233. var changed = false;
  38234. if (useClipPlane == null) {
  38235. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38236. }
  38237. if (defines["CLIPPLANE"] !== useClipPlane) {
  38238. defines["CLIPPLANE"] = useClipPlane;
  38239. changed = true;
  38240. }
  38241. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38242. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38243. changed = true;
  38244. }
  38245. if (defines["INSTANCES"] !== useInstances) {
  38246. defines["INSTANCES"] = useInstances;
  38247. changed = true;
  38248. }
  38249. if (changed) {
  38250. defines.markAsUnprocessed();
  38251. }
  38252. };
  38253. /**
  38254. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38255. * @param mesh The mesh containing the geometry data we will draw
  38256. * @param defines The defines to update
  38257. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38258. * @param useBones Precise whether bones should be used or not (override mesh info)
  38259. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38260. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38261. * @returns false if defines are considered not dirty and have not been checked
  38262. */
  38263. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38264. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38265. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38266. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38267. return false;
  38268. }
  38269. defines._normals = defines._needNormals;
  38270. defines._uvs = defines._needUVs;
  38271. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38272. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38273. defines["TANGENT"] = true;
  38274. }
  38275. if (defines._needUVs) {
  38276. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38277. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38278. }
  38279. else {
  38280. defines["UV1"] = false;
  38281. defines["UV2"] = false;
  38282. }
  38283. if (useVertexColor) {
  38284. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  38285. defines["VERTEXCOLOR"] = hasVertexColors;
  38286. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  38287. }
  38288. if (useBones) {
  38289. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38290. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  38291. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  38292. }
  38293. else {
  38294. defines["NUM_BONE_INFLUENCERS"] = 0;
  38295. defines["BonesPerMesh"] = 0;
  38296. }
  38297. }
  38298. if (useMorphTargets) {
  38299. var manager = mesh.morphTargetManager;
  38300. if (manager) {
  38301. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  38302. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  38303. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  38304. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  38305. }
  38306. else {
  38307. defines["MORPHTARGETS_TANGENT"] = false;
  38308. defines["MORPHTARGETS_NORMAL"] = false;
  38309. defines["MORPHTARGETS"] = false;
  38310. defines["NUM_MORPH_INFLUENCERS"] = 0;
  38311. }
  38312. }
  38313. return true;
  38314. };
  38315. /**
  38316. * Prepares the defines related to the light information passed in parameter
  38317. * @param scene The scene we are intending to draw
  38318. * @param mesh The mesh the effect is compiling for
  38319. * @param defines The defines to update
  38320. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  38321. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  38322. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  38323. * @returns true if normals will be required for the rest of the effect
  38324. */
  38325. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  38326. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38327. if (disableLighting === void 0) { disableLighting = false; }
  38328. if (!defines._areLightsDirty) {
  38329. return defines._needNormals;
  38330. }
  38331. var lightIndex = 0;
  38332. var needNormals = false;
  38333. var needRebuild = false;
  38334. var lightmapMode = false;
  38335. var shadowEnabled = false;
  38336. var specularEnabled = false;
  38337. if (scene.lightsEnabled && !disableLighting) {
  38338. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  38339. var light = _a[_i];
  38340. needNormals = true;
  38341. if (defines["LIGHT" + lightIndex] === undefined) {
  38342. needRebuild = true;
  38343. }
  38344. defines["LIGHT" + lightIndex] = true;
  38345. defines["SPOTLIGHT" + lightIndex] = false;
  38346. defines["HEMILIGHT" + lightIndex] = false;
  38347. defines["POINTLIGHT" + lightIndex] = false;
  38348. defines["DIRLIGHT" + lightIndex] = false;
  38349. var type;
  38350. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  38351. type = "SPOTLIGHT" + lightIndex;
  38352. var spotLight = light;
  38353. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  38354. }
  38355. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  38356. type = "HEMILIGHT" + lightIndex;
  38357. }
  38358. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  38359. type = "POINTLIGHT" + lightIndex;
  38360. }
  38361. else {
  38362. type = "DIRLIGHT" + lightIndex;
  38363. }
  38364. defines[type] = true;
  38365. // Specular
  38366. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  38367. specularEnabled = true;
  38368. }
  38369. // Shadows
  38370. defines["SHADOW" + lightIndex] = false;
  38371. defines["SHADOWPCF" + lightIndex] = false;
  38372. defines["SHADOWESM" + lightIndex] = false;
  38373. defines["SHADOWCUBE" + lightIndex] = false;
  38374. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  38375. var shadowGenerator = light.getShadowGenerator();
  38376. if (shadowGenerator) {
  38377. shadowEnabled = true;
  38378. shadowGenerator.prepareDefines(defines, lightIndex);
  38379. }
  38380. }
  38381. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  38382. lightmapMode = true;
  38383. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  38384. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  38385. }
  38386. else {
  38387. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  38388. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  38389. }
  38390. lightIndex++;
  38391. if (lightIndex === maxSimultaneousLights)
  38392. break;
  38393. }
  38394. }
  38395. defines["SPECULARTERM"] = specularEnabled;
  38396. defines["SHADOWS"] = shadowEnabled;
  38397. // Resetting all other lights if any
  38398. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  38399. if (defines["LIGHT" + index] !== undefined) {
  38400. defines["LIGHT" + index] = false;
  38401. defines["HEMILIGHT" + lightIndex] = false;
  38402. defines["POINTLIGHT" + lightIndex] = false;
  38403. defines["DIRLIGHT" + lightIndex] = false;
  38404. defines["SPOTLIGHT" + lightIndex] = false;
  38405. defines["SHADOW" + lightIndex] = false;
  38406. }
  38407. }
  38408. var caps = scene.getEngine().getCaps();
  38409. if (defines["SHADOWFLOAT"] === undefined) {
  38410. needRebuild = true;
  38411. }
  38412. defines["SHADOWFLOAT"] = shadowEnabled &&
  38413. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  38414. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  38415. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  38416. if (needRebuild) {
  38417. defines.rebuild();
  38418. }
  38419. return needNormals;
  38420. };
  38421. /**
  38422. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  38423. * that won t be acctive due to defines being turned off.
  38424. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  38425. * @param samplersList The samplers list
  38426. * @param defines The defines helping in the list generation
  38427. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  38428. */
  38429. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  38430. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38431. var uniformsList;
  38432. var uniformBuffersList = null;
  38433. if (uniformsListOrOptions.uniformsNames) {
  38434. var options = uniformsListOrOptions;
  38435. uniformsList = options.uniformsNames;
  38436. uniformBuffersList = options.uniformBuffersNames;
  38437. samplersList = options.samplers;
  38438. defines = options.defines;
  38439. maxSimultaneousLights = options.maxSimultaneousLights;
  38440. }
  38441. else {
  38442. uniformsList = uniformsListOrOptions;
  38443. if (!samplersList) {
  38444. samplersList = [];
  38445. }
  38446. }
  38447. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38448. if (!defines["LIGHT" + lightIndex]) {
  38449. break;
  38450. }
  38451. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  38452. if (uniformBuffersList) {
  38453. uniformBuffersList.push("Light" + lightIndex);
  38454. }
  38455. samplersList.push("shadowSampler" + lightIndex);
  38456. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  38457. samplersList.push("projectionLightSampler" + lightIndex);
  38458. uniformsList.push("textureProjectionMatrix" + lightIndex);
  38459. }
  38460. }
  38461. if (defines["NUM_MORPH_INFLUENCERS"]) {
  38462. uniformsList.push("morphTargetInfluences");
  38463. }
  38464. };
  38465. /**
  38466. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  38467. * @param defines The defines to update while falling back
  38468. * @param fallbacks The authorized effect fallbacks
  38469. * @param maxSimultaneousLights The maximum number of lights allowed
  38470. * @param rank the current rank of the Effect
  38471. * @returns The newly affected rank
  38472. */
  38473. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  38474. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38475. if (rank === void 0) { rank = 0; }
  38476. var lightFallbackRank = 0;
  38477. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38478. if (!defines["LIGHT" + lightIndex]) {
  38479. break;
  38480. }
  38481. if (lightIndex > 0) {
  38482. lightFallbackRank = rank + lightIndex;
  38483. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  38484. }
  38485. if (!defines["SHADOWS"]) {
  38486. if (defines["SHADOW" + lightIndex]) {
  38487. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  38488. }
  38489. if (defines["SHADOWPCF" + lightIndex]) {
  38490. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  38491. }
  38492. if (defines["SHADOWESM" + lightIndex]) {
  38493. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  38494. }
  38495. }
  38496. }
  38497. return lightFallbackRank++;
  38498. };
  38499. /**
  38500. * Prepares the list of attributes required for morph targets according to the effect defines.
  38501. * @param attribs The current list of supported attribs
  38502. * @param mesh The mesh to prepare the morph targets attributes for
  38503. * @param defines The current Defines of the effect
  38504. */
  38505. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  38506. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  38507. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  38508. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  38509. var manager = mesh.morphTargetManager;
  38510. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  38511. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  38512. for (var index = 0; index < influencers; index++) {
  38513. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  38514. if (normal) {
  38515. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  38516. }
  38517. if (tangent) {
  38518. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  38519. }
  38520. if (attribs.length > maxAttributesCount) {
  38521. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  38522. }
  38523. }
  38524. }
  38525. };
  38526. /**
  38527. * Prepares the list of attributes required for bones according to the effect defines.
  38528. * @param attribs The current list of supported attribs
  38529. * @param mesh The mesh to prepare the bones attributes for
  38530. * @param defines The current Defines of the effect
  38531. * @param fallbacks The current efffect fallback strategy
  38532. */
  38533. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  38534. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  38535. fallbacks.addCPUSkinningFallback(0, mesh);
  38536. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38537. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38538. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  38539. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38540. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38541. }
  38542. }
  38543. };
  38544. /**
  38545. * Prepares the list of attributes required for instances according to the effect defines.
  38546. * @param attribs The current list of supported attribs
  38547. * @param defines The current Defines of the effect
  38548. */
  38549. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  38550. if (defines["INSTANCES"]) {
  38551. attribs.push("world0");
  38552. attribs.push("world1");
  38553. attribs.push("world2");
  38554. attribs.push("world3");
  38555. }
  38556. };
  38557. /**
  38558. * Binds the light shadow information to the effect for the given mesh.
  38559. * @param light The light containing the generator
  38560. * @param scene The scene the lights belongs to
  38561. * @param mesh The mesh we are binding the information to render
  38562. * @param lightIndex The light index in the effect used to render the mesh
  38563. * @param effect The effect we are binding the data to
  38564. */
  38565. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  38566. if (light.shadowEnabled && mesh.receiveShadows) {
  38567. var shadowGenerator = light.getShadowGenerator();
  38568. if (shadowGenerator) {
  38569. shadowGenerator.bindShadowLight(lightIndex, effect);
  38570. }
  38571. }
  38572. };
  38573. /**
  38574. * Binds the light information to the effect.
  38575. * @param light The light containing the generator
  38576. * @param effect The effect we are binding the data to
  38577. * @param lightIndex The light index in the effect used to render
  38578. */
  38579. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  38580. light.transferToEffect(effect, lightIndex + "");
  38581. };
  38582. /**
  38583. * Binds the lights information from the scene to the effect for the given mesh.
  38584. * @param scene The scene the lights belongs to
  38585. * @param mesh The mesh we are binding the information to render
  38586. * @param effect The effect we are binding the data to
  38587. * @param defines The generated defines for the effect
  38588. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  38589. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  38590. */
  38591. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  38592. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38593. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  38594. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  38595. for (var i = 0; i < len; i++) {
  38596. var light = mesh._lightSources[i];
  38597. var iAsString = i.toString();
  38598. var scaledIntensity = light.getScaledIntensity();
  38599. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  38600. MaterialHelper.BindLightProperties(light, effect, i);
  38601. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  38602. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  38603. if (defines["SPECULARTERM"]) {
  38604. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  38605. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  38606. }
  38607. // Shadows
  38608. if (scene.shadowsEnabled) {
  38609. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  38610. }
  38611. light._uniformBuffer.update();
  38612. }
  38613. };
  38614. /**
  38615. * Binds the fog information from the scene to the effect for the given mesh.
  38616. * @param scene The scene the lights belongs to
  38617. * @param mesh The mesh we are binding the information to render
  38618. * @param effect The effect we are binding the data to
  38619. */
  38620. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  38621. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  38622. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  38623. effect.setColor3("vFogColor", scene.fogColor);
  38624. }
  38625. };
  38626. /**
  38627. * Binds the bones information from the mesh to the effect.
  38628. * @param mesh The mesh we are binding the information to render
  38629. * @param effect The effect we are binding the data to
  38630. */
  38631. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  38632. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38633. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  38634. if (matrices && effect) {
  38635. effect.setMatrices("mBones", matrices);
  38636. }
  38637. }
  38638. };
  38639. /**
  38640. * Binds the morph targets information from the mesh to the effect.
  38641. * @param abstractMesh The mesh we are binding the information to render
  38642. * @param effect The effect we are binding the data to
  38643. */
  38644. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  38645. var manager = abstractMesh.morphTargetManager;
  38646. if (!abstractMesh || !manager) {
  38647. return;
  38648. }
  38649. effect.setFloatArray("morphTargetInfluences", manager.influences);
  38650. };
  38651. /**
  38652. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  38653. * @param defines The generated defines used in the effect
  38654. * @param effect The effect we are binding the data to
  38655. * @param scene The scene we are willing to render with logarithmic scale for
  38656. */
  38657. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  38658. if (defines["LOGARITHMICDEPTH"]) {
  38659. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  38660. }
  38661. };
  38662. /**
  38663. * Binds the clip plane information from the scene to the effect.
  38664. * @param scene The scene the clip plane information are extracted from
  38665. * @param effect The effect we are binding the data to
  38666. */
  38667. MaterialHelper.BindClipPlane = function (effect, scene) {
  38668. if (scene.clipPlane) {
  38669. var clipPlane = scene.clipPlane;
  38670. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  38671. }
  38672. };
  38673. return MaterialHelper;
  38674. }());
  38675. BABYLON.MaterialHelper = MaterialHelper;
  38676. })(BABYLON || (BABYLON = {}));
  38677. //# sourceMappingURL=babylon.materialHelper.js.map
  38678. var BABYLON;
  38679. (function (BABYLON) {
  38680. var PushMaterial = /** @class */ (function (_super) {
  38681. __extends(PushMaterial, _super);
  38682. function PushMaterial(name, scene) {
  38683. var _this = _super.call(this, name, scene) || this;
  38684. _this._normalMatrix = new BABYLON.Matrix();
  38685. _this.storeEffectOnSubMeshes = true;
  38686. return _this;
  38687. }
  38688. PushMaterial.prototype.getEffect = function () {
  38689. return this._activeEffect;
  38690. };
  38691. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  38692. if (!mesh) {
  38693. return false;
  38694. }
  38695. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  38696. return true;
  38697. }
  38698. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  38699. };
  38700. /**
  38701. * Binds the given world matrix to the active effect
  38702. *
  38703. * @param world the matrix to bind
  38704. */
  38705. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38706. this._activeEffect.setMatrix("world", world);
  38707. };
  38708. /**
  38709. * Binds the given normal matrix to the active effect
  38710. *
  38711. * @param normalMatrix the matrix to bind
  38712. */
  38713. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  38714. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  38715. };
  38716. PushMaterial.prototype.bind = function (world, mesh) {
  38717. if (!mesh) {
  38718. return;
  38719. }
  38720. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  38721. };
  38722. PushMaterial.prototype._afterBind = function (mesh, effect) {
  38723. if (effect === void 0) { effect = null; }
  38724. _super.prototype._afterBind.call(this, mesh);
  38725. this.getScene()._cachedEffect = effect;
  38726. };
  38727. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  38728. if (visibility === void 0) { visibility = 1; }
  38729. return scene.isCachedMaterialInvalid(this, effect, visibility);
  38730. };
  38731. return PushMaterial;
  38732. }(BABYLON.Material));
  38733. BABYLON.PushMaterial = PushMaterial;
  38734. })(BABYLON || (BABYLON = {}));
  38735. //# sourceMappingURL=babylon.pushMaterial.js.map
  38736. var BABYLON;
  38737. (function (BABYLON) {
  38738. /** @ignore */
  38739. var StandardMaterialDefines = /** @class */ (function (_super) {
  38740. __extends(StandardMaterialDefines, _super);
  38741. function StandardMaterialDefines() {
  38742. var _this = _super.call(this) || this;
  38743. _this.MAINUV1 = false;
  38744. _this.MAINUV2 = false;
  38745. _this.DIFFUSE = false;
  38746. _this.DIFFUSEDIRECTUV = 0;
  38747. _this.AMBIENT = false;
  38748. _this.AMBIENTDIRECTUV = 0;
  38749. _this.OPACITY = false;
  38750. _this.OPACITYDIRECTUV = 0;
  38751. _this.OPACITYRGB = false;
  38752. _this.REFLECTION = false;
  38753. _this.EMISSIVE = false;
  38754. _this.EMISSIVEDIRECTUV = 0;
  38755. _this.SPECULAR = false;
  38756. _this.SPECULARDIRECTUV = 0;
  38757. _this.BUMP = false;
  38758. _this.BUMPDIRECTUV = 0;
  38759. _this.PARALLAX = false;
  38760. _this.PARALLAXOCCLUSION = false;
  38761. _this.SPECULAROVERALPHA = false;
  38762. _this.CLIPPLANE = false;
  38763. _this.ALPHATEST = false;
  38764. _this.DEPTHPREPASS = false;
  38765. _this.ALPHAFROMDIFFUSE = false;
  38766. _this.POINTSIZE = false;
  38767. _this.FOG = false;
  38768. _this.SPECULARTERM = false;
  38769. _this.DIFFUSEFRESNEL = false;
  38770. _this.OPACITYFRESNEL = false;
  38771. _this.REFLECTIONFRESNEL = false;
  38772. _this.REFRACTIONFRESNEL = false;
  38773. _this.EMISSIVEFRESNEL = false;
  38774. _this.FRESNEL = false;
  38775. _this.NORMAL = false;
  38776. _this.UV1 = false;
  38777. _this.UV2 = false;
  38778. _this.VERTEXCOLOR = false;
  38779. _this.VERTEXALPHA = false;
  38780. _this.NUM_BONE_INFLUENCERS = 0;
  38781. _this.BonesPerMesh = 0;
  38782. _this.INSTANCES = false;
  38783. _this.GLOSSINESS = false;
  38784. _this.ROUGHNESS = false;
  38785. _this.EMISSIVEASILLUMINATION = false;
  38786. _this.LINKEMISSIVEWITHDIFFUSE = false;
  38787. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  38788. _this.LIGHTMAP = false;
  38789. _this.LIGHTMAPDIRECTUV = 0;
  38790. _this.OBJECTSPACE_NORMALMAP = false;
  38791. _this.USELIGHTMAPASSHADOWMAP = false;
  38792. _this.REFLECTIONMAP_3D = false;
  38793. _this.REFLECTIONMAP_SPHERICAL = false;
  38794. _this.REFLECTIONMAP_PLANAR = false;
  38795. _this.REFLECTIONMAP_CUBIC = false;
  38796. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  38797. _this.REFLECTIONMAP_PROJECTION = false;
  38798. _this.REFLECTIONMAP_SKYBOX = false;
  38799. _this.REFLECTIONMAP_EXPLICIT = false;
  38800. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38801. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38802. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38803. _this.INVERTCUBICMAP = false;
  38804. _this.LOGARITHMICDEPTH = false;
  38805. _this.REFRACTION = false;
  38806. _this.REFRACTIONMAP_3D = false;
  38807. _this.REFLECTIONOVERALPHA = false;
  38808. _this.TWOSIDEDLIGHTING = false;
  38809. _this.SHADOWFLOAT = false;
  38810. _this.MORPHTARGETS = false;
  38811. _this.MORPHTARGETS_NORMAL = false;
  38812. _this.MORPHTARGETS_TANGENT = false;
  38813. _this.NUM_MORPH_INFLUENCERS = 0;
  38814. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  38815. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  38816. _this.IMAGEPROCESSING = false;
  38817. _this.VIGNETTE = false;
  38818. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  38819. _this.VIGNETTEBLENDMODEOPAQUE = false;
  38820. _this.TONEMAPPING = false;
  38821. _this.CONTRAST = false;
  38822. _this.COLORCURVES = false;
  38823. _this.COLORGRADING = false;
  38824. _this.COLORGRADING3D = false;
  38825. _this.SAMPLER3DGREENDEPTH = false;
  38826. _this.SAMPLER3DBGRMAP = false;
  38827. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  38828. _this.EXPOSURE = false;
  38829. _this.rebuild();
  38830. return _this;
  38831. }
  38832. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  38833. var modes = [
  38834. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  38835. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  38836. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  38837. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  38838. ];
  38839. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  38840. var mode = modes_1[_i];
  38841. this[mode] = (mode === modeToEnable);
  38842. }
  38843. };
  38844. return StandardMaterialDefines;
  38845. }(BABYLON.MaterialDefines));
  38846. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  38847. var StandardMaterial = /** @class */ (function (_super) {
  38848. __extends(StandardMaterial, _super);
  38849. function StandardMaterial(name, scene) {
  38850. var _this = _super.call(this, name, scene) || this;
  38851. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  38852. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  38853. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  38854. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38855. _this.specularPower = 64;
  38856. _this._useAlphaFromDiffuseTexture = false;
  38857. _this._useEmissiveAsIllumination = false;
  38858. _this._linkEmissiveWithDiffuse = false;
  38859. _this._useSpecularOverAlpha = false;
  38860. _this._useReflectionOverAlpha = false;
  38861. _this._disableLighting = false;
  38862. _this._useObjectSpaceNormalMap = false;
  38863. _this._useParallax = false;
  38864. _this._useParallaxOcclusion = false;
  38865. _this.parallaxScaleBias = 0.05;
  38866. _this._roughness = 0;
  38867. _this.indexOfRefraction = 0.98;
  38868. _this.invertRefractionY = true;
  38869. _this._useLightmapAsShadowmap = false;
  38870. _this._useReflectionFresnelFromSpecular = false;
  38871. _this._useGlossinessFromSpecularMapAlpha = false;
  38872. _this._maxSimultaneousLights = 4;
  38873. /**
  38874. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38875. */
  38876. _this._invertNormalMapX = false;
  38877. /**
  38878. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38879. */
  38880. _this._invertNormalMapY = false;
  38881. /**
  38882. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38883. */
  38884. _this._twoSidedLighting = false;
  38885. _this._renderTargets = new BABYLON.SmartArray(16);
  38886. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  38887. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  38888. // Setup the default processing configuration to the scene.
  38889. _this._attachImageProcessingConfiguration(null);
  38890. _this.getRenderTargetTextures = function () {
  38891. _this._renderTargets.reset();
  38892. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  38893. _this._renderTargets.push(_this._reflectionTexture);
  38894. }
  38895. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  38896. _this._renderTargets.push(_this._refractionTexture);
  38897. }
  38898. return _this._renderTargets;
  38899. };
  38900. return _this;
  38901. }
  38902. ;
  38903. ;
  38904. ;
  38905. ;
  38906. ;
  38907. ;
  38908. ;
  38909. ;
  38910. ;
  38911. ;
  38912. ;
  38913. ;
  38914. ;
  38915. ;
  38916. ;
  38917. ;
  38918. ;
  38919. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  38920. /**
  38921. * Gets the image processing configuration used either in this material.
  38922. */
  38923. get: function () {
  38924. return this._imageProcessingConfiguration;
  38925. },
  38926. /**
  38927. * Sets the Default image processing configuration used either in the this material.
  38928. *
  38929. * If sets to null, the scene one is in use.
  38930. */
  38931. set: function (value) {
  38932. this._attachImageProcessingConfiguration(value);
  38933. // Ensure the effect will be rebuilt.
  38934. this._markAllSubMeshesAsTexturesDirty();
  38935. },
  38936. enumerable: true,
  38937. configurable: true
  38938. });
  38939. /**
  38940. * Attaches a new image processing configuration to the Standard Material.
  38941. * @param configuration
  38942. */
  38943. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  38944. var _this = this;
  38945. if (configuration === this._imageProcessingConfiguration) {
  38946. return;
  38947. }
  38948. // Detaches observer.
  38949. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38950. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38951. }
  38952. // Pick the scene configuration if needed.
  38953. if (!configuration) {
  38954. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  38955. }
  38956. else {
  38957. this._imageProcessingConfiguration = configuration;
  38958. }
  38959. // Attaches observer.
  38960. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  38961. _this._markAllSubMeshesAsImageProcessingDirty();
  38962. });
  38963. };
  38964. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  38965. /**
  38966. * Gets wether the color curves effect is enabled.
  38967. */
  38968. get: function () {
  38969. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38970. },
  38971. /**
  38972. * Sets wether the color curves effect is enabled.
  38973. */
  38974. set: function (value) {
  38975. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38976. },
  38977. enumerable: true,
  38978. configurable: true
  38979. });
  38980. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  38981. /**
  38982. * Gets wether the color grading effect is enabled.
  38983. */
  38984. get: function () {
  38985. return this.imageProcessingConfiguration.colorGradingEnabled;
  38986. },
  38987. /**
  38988. * Gets wether the color grading effect is enabled.
  38989. */
  38990. set: function (value) {
  38991. this.imageProcessingConfiguration.colorGradingEnabled = value;
  38992. },
  38993. enumerable: true,
  38994. configurable: true
  38995. });
  38996. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  38997. /**
  38998. * Gets wether tonemapping is enabled or not.
  38999. */
  39000. get: function () {
  39001. return this._imageProcessingConfiguration.toneMappingEnabled;
  39002. },
  39003. /**
  39004. * Sets wether tonemapping is enabled or not
  39005. */
  39006. set: function (value) {
  39007. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39008. },
  39009. enumerable: true,
  39010. configurable: true
  39011. });
  39012. ;
  39013. ;
  39014. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  39015. /**
  39016. * The camera exposure used on this material.
  39017. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39018. * This corresponds to a photographic exposure.
  39019. */
  39020. get: function () {
  39021. return this._imageProcessingConfiguration.exposure;
  39022. },
  39023. /**
  39024. * The camera exposure used on this material.
  39025. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39026. * This corresponds to a photographic exposure.
  39027. */
  39028. set: function (value) {
  39029. this._imageProcessingConfiguration.exposure = value;
  39030. },
  39031. enumerable: true,
  39032. configurable: true
  39033. });
  39034. ;
  39035. ;
  39036. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  39037. /**
  39038. * Gets The camera contrast used on this material.
  39039. */
  39040. get: function () {
  39041. return this._imageProcessingConfiguration.contrast;
  39042. },
  39043. /**
  39044. * Sets The camera contrast used on this material.
  39045. */
  39046. set: function (value) {
  39047. this._imageProcessingConfiguration.contrast = value;
  39048. },
  39049. enumerable: true,
  39050. configurable: true
  39051. });
  39052. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  39053. /**
  39054. * Gets the Color Grading 2D Lookup Texture.
  39055. */
  39056. get: function () {
  39057. return this._imageProcessingConfiguration.colorGradingTexture;
  39058. },
  39059. /**
  39060. * Sets the Color Grading 2D Lookup Texture.
  39061. */
  39062. set: function (value) {
  39063. this._imageProcessingConfiguration.colorGradingTexture = value;
  39064. },
  39065. enumerable: true,
  39066. configurable: true
  39067. });
  39068. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39069. /**
  39070. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39071. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39072. * 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;
  39073. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39074. */
  39075. get: function () {
  39076. return this._imageProcessingConfiguration.colorCurves;
  39077. },
  39078. /**
  39079. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39080. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39081. * 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;
  39082. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39083. */
  39084. set: function (value) {
  39085. this._imageProcessingConfiguration.colorCurves = value;
  39086. },
  39087. enumerable: true,
  39088. configurable: true
  39089. });
  39090. StandardMaterial.prototype.getClassName = function () {
  39091. return "StandardMaterial";
  39092. };
  39093. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39094. get: function () {
  39095. return this._useLogarithmicDepth;
  39096. },
  39097. set: function (value) {
  39098. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39099. this._markAllSubMeshesAsMiscDirty();
  39100. },
  39101. enumerable: true,
  39102. configurable: true
  39103. });
  39104. StandardMaterial.prototype.needAlphaBlending = function () {
  39105. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39106. };
  39107. StandardMaterial.prototype.needAlphaTesting = function () {
  39108. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39109. };
  39110. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39111. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39112. };
  39113. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39114. return this._diffuseTexture;
  39115. };
  39116. /**
  39117. * Child classes can use it to update shaders
  39118. */
  39119. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39120. if (useInstances === void 0) { useInstances = false; }
  39121. if (subMesh.effect && this.isFrozen) {
  39122. if (this._wasPreviouslyReady && subMesh.effect) {
  39123. return true;
  39124. }
  39125. }
  39126. if (!subMesh._materialDefines) {
  39127. subMesh._materialDefines = new StandardMaterialDefines();
  39128. }
  39129. var scene = this.getScene();
  39130. var defines = subMesh._materialDefines;
  39131. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39132. if (defines._renderId === scene.getRenderId()) {
  39133. return true;
  39134. }
  39135. }
  39136. var engine = scene.getEngine();
  39137. // Lights
  39138. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39139. // Textures
  39140. if (defines._areTexturesDirty) {
  39141. defines._needUVs = false;
  39142. defines.MAINUV1 = false;
  39143. defines.MAINUV2 = false;
  39144. if (scene.texturesEnabled) {
  39145. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39146. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39147. return false;
  39148. }
  39149. else {
  39150. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39151. }
  39152. }
  39153. else {
  39154. defines.DIFFUSE = false;
  39155. }
  39156. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39157. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39158. return false;
  39159. }
  39160. else {
  39161. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39162. }
  39163. }
  39164. else {
  39165. defines.AMBIENT = false;
  39166. }
  39167. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39168. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39169. return false;
  39170. }
  39171. else {
  39172. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39173. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39174. }
  39175. }
  39176. else {
  39177. defines.OPACITY = false;
  39178. }
  39179. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39180. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39181. return false;
  39182. }
  39183. else {
  39184. defines._needNormals = true;
  39185. defines.REFLECTION = true;
  39186. defines.ROUGHNESS = (this._roughness > 0);
  39187. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39188. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39189. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39190. switch (this._reflectionTexture.coordinatesMode) {
  39191. case BABYLON.Texture.CUBIC_MODE:
  39192. case BABYLON.Texture.INVCUBIC_MODE:
  39193. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39194. break;
  39195. case BABYLON.Texture.EXPLICIT_MODE:
  39196. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39197. break;
  39198. case BABYLON.Texture.PLANAR_MODE:
  39199. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39200. break;
  39201. case BABYLON.Texture.PROJECTION_MODE:
  39202. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39203. break;
  39204. case BABYLON.Texture.SKYBOX_MODE:
  39205. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39206. break;
  39207. case BABYLON.Texture.SPHERICAL_MODE:
  39208. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39209. break;
  39210. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39211. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39212. break;
  39213. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39214. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39215. break;
  39216. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39217. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39218. break;
  39219. }
  39220. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39221. }
  39222. }
  39223. else {
  39224. defines.REFLECTION = false;
  39225. }
  39226. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39227. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39228. return false;
  39229. }
  39230. else {
  39231. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39232. }
  39233. }
  39234. else {
  39235. defines.EMISSIVE = false;
  39236. }
  39237. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39238. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39239. return false;
  39240. }
  39241. else {
  39242. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39243. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39244. }
  39245. }
  39246. else {
  39247. defines.LIGHTMAP = false;
  39248. }
  39249. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39250. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39251. return false;
  39252. }
  39253. else {
  39254. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39255. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39256. }
  39257. }
  39258. else {
  39259. defines.SPECULAR = false;
  39260. }
  39261. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39262. // Bump texure can not be not blocking.
  39263. if (!this._bumpTexture.isReady()) {
  39264. return false;
  39265. }
  39266. else {
  39267. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  39268. defines.PARALLAX = this._useParallax;
  39269. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  39270. }
  39271. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  39272. }
  39273. else {
  39274. defines.BUMP = false;
  39275. }
  39276. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39277. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  39278. return false;
  39279. }
  39280. else {
  39281. defines._needUVs = true;
  39282. defines.REFRACTION = true;
  39283. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  39284. }
  39285. }
  39286. else {
  39287. defines.REFRACTION = false;
  39288. }
  39289. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  39290. }
  39291. else {
  39292. defines.DIFFUSE = false;
  39293. defines.AMBIENT = false;
  39294. defines.OPACITY = false;
  39295. defines.REFLECTION = false;
  39296. defines.EMISSIVE = false;
  39297. defines.LIGHTMAP = false;
  39298. defines.BUMP = false;
  39299. defines.REFRACTION = false;
  39300. }
  39301. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  39302. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  39303. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  39304. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  39305. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  39306. }
  39307. if (defines._areImageProcessingDirty) {
  39308. if (!this._imageProcessingConfiguration.isReady()) {
  39309. return false;
  39310. }
  39311. this._imageProcessingConfiguration.prepareDefines(defines);
  39312. }
  39313. if (defines._areFresnelDirty) {
  39314. if (StandardMaterial.FresnelEnabled) {
  39315. // Fresnel
  39316. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  39317. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  39318. this._reflectionFresnelParameters) {
  39319. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  39320. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  39321. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  39322. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  39323. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  39324. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  39325. defines._needNormals = true;
  39326. defines.FRESNEL = true;
  39327. }
  39328. }
  39329. else {
  39330. defines.FRESNEL = false;
  39331. }
  39332. }
  39333. // Misc.
  39334. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  39335. // Attribs
  39336. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  39337. // Values that need to be evaluated on every frame
  39338. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  39339. // Get correct effect
  39340. if (defines.isDirty) {
  39341. defines.markAsProcessed();
  39342. scene.resetCachedMaterial();
  39343. // Fallbacks
  39344. var fallbacks = new BABYLON.EffectFallbacks();
  39345. if (defines.REFLECTION) {
  39346. fallbacks.addFallback(0, "REFLECTION");
  39347. }
  39348. if (defines.SPECULAR) {
  39349. fallbacks.addFallback(0, "SPECULAR");
  39350. }
  39351. if (defines.BUMP) {
  39352. fallbacks.addFallback(0, "BUMP");
  39353. }
  39354. if (defines.PARALLAX) {
  39355. fallbacks.addFallback(1, "PARALLAX");
  39356. }
  39357. if (defines.PARALLAXOCCLUSION) {
  39358. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  39359. }
  39360. if (defines.SPECULAROVERALPHA) {
  39361. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  39362. }
  39363. if (defines.FOG) {
  39364. fallbacks.addFallback(1, "FOG");
  39365. }
  39366. if (defines.POINTSIZE) {
  39367. fallbacks.addFallback(0, "POINTSIZE");
  39368. }
  39369. if (defines.LOGARITHMICDEPTH) {
  39370. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  39371. }
  39372. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  39373. if (defines.SPECULARTERM) {
  39374. fallbacks.addFallback(0, "SPECULARTERM");
  39375. }
  39376. if (defines.DIFFUSEFRESNEL) {
  39377. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  39378. }
  39379. if (defines.OPACITYFRESNEL) {
  39380. fallbacks.addFallback(2, "OPACITYFRESNEL");
  39381. }
  39382. if (defines.REFLECTIONFRESNEL) {
  39383. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  39384. }
  39385. if (defines.EMISSIVEFRESNEL) {
  39386. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  39387. }
  39388. if (defines.FRESNEL) {
  39389. fallbacks.addFallback(4, "FRESNEL");
  39390. }
  39391. //Attributes
  39392. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39393. if (defines.NORMAL) {
  39394. attribs.push(BABYLON.VertexBuffer.NormalKind);
  39395. }
  39396. if (defines.UV1) {
  39397. attribs.push(BABYLON.VertexBuffer.UVKind);
  39398. }
  39399. if (defines.UV2) {
  39400. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39401. }
  39402. if (defines.VERTEXCOLOR) {
  39403. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39404. }
  39405. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  39406. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  39407. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  39408. var shaderName = "default";
  39409. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  39410. "vFogInfos", "vFogColor", "pointSize",
  39411. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  39412. "mBones",
  39413. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  39414. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  39415. "vReflectionPosition", "vReflectionSize",
  39416. "logarithmicDepthConstant", "vTangentSpaceParams"
  39417. ];
  39418. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  39419. var uniformBuffers = ["Material", "Scene"];
  39420. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  39421. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  39422. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  39423. uniformsNames: uniforms,
  39424. uniformBuffersNames: uniformBuffers,
  39425. samplers: samplers,
  39426. defines: defines,
  39427. maxSimultaneousLights: this._maxSimultaneousLights
  39428. });
  39429. if (this.customShaderNameResolve) {
  39430. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  39431. }
  39432. var join = defines.toString();
  39433. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  39434. attributes: attribs,
  39435. uniformsNames: uniforms,
  39436. uniformBuffersNames: uniformBuffers,
  39437. samplers: samplers,
  39438. defines: join,
  39439. fallbacks: fallbacks,
  39440. onCompiled: this.onCompiled,
  39441. onError: this.onError,
  39442. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  39443. }, engine), defines);
  39444. this.buildUniformLayout();
  39445. }
  39446. if (!subMesh.effect || !subMesh.effect.isReady()) {
  39447. return false;
  39448. }
  39449. defines._renderId = scene.getRenderId();
  39450. this._wasPreviouslyReady = true;
  39451. return true;
  39452. };
  39453. StandardMaterial.prototype.buildUniformLayout = function () {
  39454. // Order is important !
  39455. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  39456. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  39457. this._uniformBuffer.addUniform("opacityParts", 4);
  39458. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  39459. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  39460. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  39461. this._uniformBuffer.addUniform("refractionRightColor", 4);
  39462. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  39463. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  39464. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  39465. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  39466. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  39467. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  39468. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  39469. this._uniformBuffer.addUniform("vReflectionSize", 3);
  39470. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  39471. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  39472. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  39473. this._uniformBuffer.addUniform("vBumpInfos", 3);
  39474. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  39475. this._uniformBuffer.addUniform("ambientMatrix", 16);
  39476. this._uniformBuffer.addUniform("opacityMatrix", 16);
  39477. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  39478. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  39479. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  39480. this._uniformBuffer.addUniform("specularMatrix", 16);
  39481. this._uniformBuffer.addUniform("bumpMatrix", 16);
  39482. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  39483. this._uniformBuffer.addUniform("refractionMatrix", 16);
  39484. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  39485. this._uniformBuffer.addUniform("vSpecularColor", 4);
  39486. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  39487. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  39488. this._uniformBuffer.addUniform("pointSize", 1);
  39489. this._uniformBuffer.create();
  39490. };
  39491. StandardMaterial.prototype.unbind = function () {
  39492. if (this._activeEffect) {
  39493. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  39494. this._activeEffect.setTexture("reflection2DSampler", null);
  39495. }
  39496. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  39497. this._activeEffect.setTexture("refraction2DSampler", null);
  39498. }
  39499. }
  39500. _super.prototype.unbind.call(this);
  39501. };
  39502. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  39503. var scene = this.getScene();
  39504. var defines = subMesh._materialDefines;
  39505. if (!defines) {
  39506. return;
  39507. }
  39508. var effect = subMesh.effect;
  39509. if (!effect) {
  39510. return;
  39511. }
  39512. this._activeEffect = effect;
  39513. // Matrices
  39514. this.bindOnlyWorldMatrix(world);
  39515. // Normal Matrix
  39516. if (defines.OBJECTSPACE_NORMALMAP) {
  39517. world.toNormalMatrix(this._normalMatrix);
  39518. this.bindOnlyNormalMatrix(this._normalMatrix);
  39519. }
  39520. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  39521. // Bones
  39522. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  39523. if (mustRebind) {
  39524. this._uniformBuffer.bindToEffect(effect, "Material");
  39525. this.bindViewProjection(effect);
  39526. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  39527. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  39528. // Fresnel
  39529. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  39530. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  39531. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  39532. }
  39533. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  39534. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  39535. }
  39536. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  39537. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  39538. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  39539. }
  39540. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  39541. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  39542. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  39543. }
  39544. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  39545. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  39546. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  39547. }
  39548. }
  39549. // Textures
  39550. if (scene.texturesEnabled) {
  39551. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39552. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  39553. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  39554. }
  39555. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39556. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  39557. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  39558. }
  39559. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39560. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  39561. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  39562. }
  39563. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39564. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  39565. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  39566. if (this._reflectionTexture.boundingBoxSize) {
  39567. var cubeTexture = this._reflectionTexture;
  39568. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  39569. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  39570. }
  39571. }
  39572. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39573. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  39574. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  39575. }
  39576. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39577. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  39578. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  39579. }
  39580. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39581. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  39582. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  39583. }
  39584. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39585. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  39586. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  39587. if (scene._mirroredCameraPosition) {
  39588. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  39589. }
  39590. else {
  39591. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  39592. }
  39593. }
  39594. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39595. var depth = 1.0;
  39596. if (!this._refractionTexture.isCube) {
  39597. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  39598. if (this._refractionTexture.depth) {
  39599. depth = this._refractionTexture.depth;
  39600. }
  39601. }
  39602. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  39603. }
  39604. }
  39605. // Point size
  39606. if (this.pointsCloud) {
  39607. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39608. }
  39609. if (defines.SPECULARTERM) {
  39610. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  39611. }
  39612. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  39613. // Diffuse
  39614. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  39615. }
  39616. // Textures
  39617. if (scene.texturesEnabled) {
  39618. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39619. effect.setTexture("diffuseSampler", this._diffuseTexture);
  39620. }
  39621. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39622. effect.setTexture("ambientSampler", this._ambientTexture);
  39623. }
  39624. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39625. effect.setTexture("opacitySampler", this._opacityTexture);
  39626. }
  39627. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39628. if (this._reflectionTexture.isCube) {
  39629. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  39630. }
  39631. else {
  39632. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  39633. }
  39634. }
  39635. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39636. effect.setTexture("emissiveSampler", this._emissiveTexture);
  39637. }
  39638. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39639. effect.setTexture("lightmapSampler", this._lightmapTexture);
  39640. }
  39641. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39642. effect.setTexture("specularSampler", this._specularTexture);
  39643. }
  39644. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39645. effect.setTexture("bumpSampler", this._bumpTexture);
  39646. }
  39647. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39648. var depth = 1.0;
  39649. if (this._refractionTexture.isCube) {
  39650. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  39651. }
  39652. else {
  39653. effect.setTexture("refraction2DSampler", this._refractionTexture);
  39654. }
  39655. }
  39656. }
  39657. // Clip plane
  39658. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  39659. // Colors
  39660. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  39661. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  39662. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39663. }
  39664. if (mustRebind || !this.isFrozen) {
  39665. // Lights
  39666. if (scene.lightsEnabled && !this._disableLighting) {
  39667. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  39668. }
  39669. // View
  39670. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  39671. this.bindView(effect);
  39672. }
  39673. // Fog
  39674. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  39675. // Morph targets
  39676. if (defines.NUM_MORPH_INFLUENCERS) {
  39677. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  39678. }
  39679. // Log. depth
  39680. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  39681. // image processing
  39682. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  39683. this._imageProcessingConfiguration.bind(this._activeEffect);
  39684. }
  39685. }
  39686. this._uniformBuffer.update();
  39687. this._afterBind(mesh, this._activeEffect);
  39688. };
  39689. StandardMaterial.prototype.getAnimatables = function () {
  39690. var results = [];
  39691. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  39692. results.push(this._diffuseTexture);
  39693. }
  39694. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39695. results.push(this._ambientTexture);
  39696. }
  39697. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39698. results.push(this._opacityTexture);
  39699. }
  39700. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39701. results.push(this._reflectionTexture);
  39702. }
  39703. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39704. results.push(this._emissiveTexture);
  39705. }
  39706. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  39707. results.push(this._specularTexture);
  39708. }
  39709. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39710. results.push(this._bumpTexture);
  39711. }
  39712. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39713. results.push(this._lightmapTexture);
  39714. }
  39715. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39716. results.push(this._refractionTexture);
  39717. }
  39718. return results;
  39719. };
  39720. StandardMaterial.prototype.getActiveTextures = function () {
  39721. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39722. if (this._diffuseTexture) {
  39723. activeTextures.push(this._diffuseTexture);
  39724. }
  39725. if (this._ambientTexture) {
  39726. activeTextures.push(this._ambientTexture);
  39727. }
  39728. if (this._opacityTexture) {
  39729. activeTextures.push(this._opacityTexture);
  39730. }
  39731. if (this._reflectionTexture) {
  39732. activeTextures.push(this._reflectionTexture);
  39733. }
  39734. if (this._emissiveTexture) {
  39735. activeTextures.push(this._emissiveTexture);
  39736. }
  39737. if (this._specularTexture) {
  39738. activeTextures.push(this._specularTexture);
  39739. }
  39740. if (this._bumpTexture) {
  39741. activeTextures.push(this._bumpTexture);
  39742. }
  39743. if (this._lightmapTexture) {
  39744. activeTextures.push(this._lightmapTexture);
  39745. }
  39746. if (this._refractionTexture) {
  39747. activeTextures.push(this._refractionTexture);
  39748. }
  39749. return activeTextures;
  39750. };
  39751. StandardMaterial.prototype.hasTexture = function (texture) {
  39752. if (_super.prototype.hasTexture.call(this, texture)) {
  39753. return true;
  39754. }
  39755. if (this._diffuseTexture === texture) {
  39756. return true;
  39757. }
  39758. if (this._ambientTexture === texture) {
  39759. return true;
  39760. }
  39761. if (this._opacityTexture === texture) {
  39762. return true;
  39763. }
  39764. if (this._reflectionTexture === texture) {
  39765. return true;
  39766. }
  39767. if (this._emissiveTexture === texture) {
  39768. return true;
  39769. }
  39770. if (this._specularTexture === texture) {
  39771. return true;
  39772. }
  39773. if (this._bumpTexture === texture) {
  39774. return true;
  39775. }
  39776. if (this._lightmapTexture === texture) {
  39777. return true;
  39778. }
  39779. if (this._refractionTexture === texture) {
  39780. return true;
  39781. }
  39782. return false;
  39783. };
  39784. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39785. if (forceDisposeTextures) {
  39786. if (this._diffuseTexture) {
  39787. this._diffuseTexture.dispose();
  39788. }
  39789. if (this._ambientTexture) {
  39790. this._ambientTexture.dispose();
  39791. }
  39792. if (this._opacityTexture) {
  39793. this._opacityTexture.dispose();
  39794. }
  39795. if (this._reflectionTexture) {
  39796. this._reflectionTexture.dispose();
  39797. }
  39798. if (this._emissiveTexture) {
  39799. this._emissiveTexture.dispose();
  39800. }
  39801. if (this._specularTexture) {
  39802. this._specularTexture.dispose();
  39803. }
  39804. if (this._bumpTexture) {
  39805. this._bumpTexture.dispose();
  39806. }
  39807. if (this._lightmapTexture) {
  39808. this._lightmapTexture.dispose();
  39809. }
  39810. if (this._refractionTexture) {
  39811. this._refractionTexture.dispose();
  39812. }
  39813. }
  39814. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39815. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39816. }
  39817. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39818. };
  39819. StandardMaterial.prototype.clone = function (name) {
  39820. var _this = this;
  39821. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  39822. result.name = name;
  39823. result.id = name;
  39824. return result;
  39825. };
  39826. StandardMaterial.prototype.serialize = function () {
  39827. return BABYLON.SerializationHelper.Serialize(this);
  39828. };
  39829. // Statics
  39830. StandardMaterial.Parse = function (source, scene, rootUrl) {
  39831. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  39832. };
  39833. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  39834. get: function () {
  39835. return StandardMaterial._DiffuseTextureEnabled;
  39836. },
  39837. set: function (value) {
  39838. if (StandardMaterial._DiffuseTextureEnabled === value) {
  39839. return;
  39840. }
  39841. StandardMaterial._DiffuseTextureEnabled = value;
  39842. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39843. },
  39844. enumerable: true,
  39845. configurable: true
  39846. });
  39847. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  39848. get: function () {
  39849. return StandardMaterial._AmbientTextureEnabled;
  39850. },
  39851. set: function (value) {
  39852. if (StandardMaterial._AmbientTextureEnabled === value) {
  39853. return;
  39854. }
  39855. StandardMaterial._AmbientTextureEnabled = value;
  39856. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39857. },
  39858. enumerable: true,
  39859. configurable: true
  39860. });
  39861. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  39862. get: function () {
  39863. return StandardMaterial._OpacityTextureEnabled;
  39864. },
  39865. set: function (value) {
  39866. if (StandardMaterial._OpacityTextureEnabled === value) {
  39867. return;
  39868. }
  39869. StandardMaterial._OpacityTextureEnabled = value;
  39870. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39871. },
  39872. enumerable: true,
  39873. configurable: true
  39874. });
  39875. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  39876. get: function () {
  39877. return StandardMaterial._ReflectionTextureEnabled;
  39878. },
  39879. set: function (value) {
  39880. if (StandardMaterial._ReflectionTextureEnabled === value) {
  39881. return;
  39882. }
  39883. StandardMaterial._ReflectionTextureEnabled = value;
  39884. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39885. },
  39886. enumerable: true,
  39887. configurable: true
  39888. });
  39889. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  39890. get: function () {
  39891. return StandardMaterial._EmissiveTextureEnabled;
  39892. },
  39893. set: function (value) {
  39894. if (StandardMaterial._EmissiveTextureEnabled === value) {
  39895. return;
  39896. }
  39897. StandardMaterial._EmissiveTextureEnabled = value;
  39898. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39899. },
  39900. enumerable: true,
  39901. configurable: true
  39902. });
  39903. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  39904. get: function () {
  39905. return StandardMaterial._SpecularTextureEnabled;
  39906. },
  39907. set: function (value) {
  39908. if (StandardMaterial._SpecularTextureEnabled === value) {
  39909. return;
  39910. }
  39911. StandardMaterial._SpecularTextureEnabled = value;
  39912. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39913. },
  39914. enumerable: true,
  39915. configurable: true
  39916. });
  39917. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  39918. get: function () {
  39919. return StandardMaterial._BumpTextureEnabled;
  39920. },
  39921. set: function (value) {
  39922. if (StandardMaterial._BumpTextureEnabled === value) {
  39923. return;
  39924. }
  39925. StandardMaterial._BumpTextureEnabled = value;
  39926. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39927. },
  39928. enumerable: true,
  39929. configurable: true
  39930. });
  39931. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  39932. get: function () {
  39933. return StandardMaterial._LightmapTextureEnabled;
  39934. },
  39935. set: function (value) {
  39936. if (StandardMaterial._LightmapTextureEnabled === value) {
  39937. return;
  39938. }
  39939. StandardMaterial._LightmapTextureEnabled = value;
  39940. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39941. },
  39942. enumerable: true,
  39943. configurable: true
  39944. });
  39945. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  39946. get: function () {
  39947. return StandardMaterial._RefractionTextureEnabled;
  39948. },
  39949. set: function (value) {
  39950. if (StandardMaterial._RefractionTextureEnabled === value) {
  39951. return;
  39952. }
  39953. StandardMaterial._RefractionTextureEnabled = value;
  39954. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39955. },
  39956. enumerable: true,
  39957. configurable: true
  39958. });
  39959. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  39960. get: function () {
  39961. return StandardMaterial._ColorGradingTextureEnabled;
  39962. },
  39963. set: function (value) {
  39964. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  39965. return;
  39966. }
  39967. StandardMaterial._ColorGradingTextureEnabled = value;
  39968. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39969. },
  39970. enumerable: true,
  39971. configurable: true
  39972. });
  39973. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  39974. get: function () {
  39975. return StandardMaterial._FresnelEnabled;
  39976. },
  39977. set: function (value) {
  39978. if (StandardMaterial._FresnelEnabled === value) {
  39979. return;
  39980. }
  39981. StandardMaterial._FresnelEnabled = value;
  39982. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  39983. },
  39984. enumerable: true,
  39985. configurable: true
  39986. });
  39987. // Flags used to enable or disable a type of texture for all Standard Materials
  39988. StandardMaterial._DiffuseTextureEnabled = true;
  39989. StandardMaterial._AmbientTextureEnabled = true;
  39990. StandardMaterial._OpacityTextureEnabled = true;
  39991. StandardMaterial._ReflectionTextureEnabled = true;
  39992. StandardMaterial._EmissiveTextureEnabled = true;
  39993. StandardMaterial._SpecularTextureEnabled = true;
  39994. StandardMaterial._BumpTextureEnabled = true;
  39995. StandardMaterial._LightmapTextureEnabled = true;
  39996. StandardMaterial._RefractionTextureEnabled = true;
  39997. StandardMaterial._ColorGradingTextureEnabled = true;
  39998. StandardMaterial._FresnelEnabled = true;
  39999. __decorate([
  40000. BABYLON.serializeAsTexture("diffuseTexture")
  40001. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  40002. __decorate([
  40003. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40004. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  40005. __decorate([
  40006. BABYLON.serializeAsTexture("ambientTexture")
  40007. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  40008. __decorate([
  40009. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40010. ], StandardMaterial.prototype, "ambientTexture", void 0);
  40011. __decorate([
  40012. BABYLON.serializeAsTexture("opacityTexture")
  40013. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  40014. __decorate([
  40015. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40016. ], StandardMaterial.prototype, "opacityTexture", void 0);
  40017. __decorate([
  40018. BABYLON.serializeAsTexture("reflectionTexture")
  40019. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  40020. __decorate([
  40021. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40022. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  40023. __decorate([
  40024. BABYLON.serializeAsTexture("emissiveTexture")
  40025. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  40026. __decorate([
  40027. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40028. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  40029. __decorate([
  40030. BABYLON.serializeAsTexture("specularTexture")
  40031. ], StandardMaterial.prototype, "_specularTexture", void 0);
  40032. __decorate([
  40033. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40034. ], StandardMaterial.prototype, "specularTexture", void 0);
  40035. __decorate([
  40036. BABYLON.serializeAsTexture("bumpTexture")
  40037. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  40038. __decorate([
  40039. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40040. ], StandardMaterial.prototype, "bumpTexture", void 0);
  40041. __decorate([
  40042. BABYLON.serializeAsTexture("lightmapTexture")
  40043. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  40044. __decorate([
  40045. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40046. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  40047. __decorate([
  40048. BABYLON.serializeAsTexture("refractionTexture")
  40049. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  40050. __decorate([
  40051. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40052. ], StandardMaterial.prototype, "refractionTexture", void 0);
  40053. __decorate([
  40054. BABYLON.serializeAsColor3("ambient")
  40055. ], StandardMaterial.prototype, "ambientColor", void 0);
  40056. __decorate([
  40057. BABYLON.serializeAsColor3("diffuse")
  40058. ], StandardMaterial.prototype, "diffuseColor", void 0);
  40059. __decorate([
  40060. BABYLON.serializeAsColor3("specular")
  40061. ], StandardMaterial.prototype, "specularColor", void 0);
  40062. __decorate([
  40063. BABYLON.serializeAsColor3("emissive")
  40064. ], StandardMaterial.prototype, "emissiveColor", void 0);
  40065. __decorate([
  40066. BABYLON.serialize()
  40067. ], StandardMaterial.prototype, "specularPower", void 0);
  40068. __decorate([
  40069. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40070. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40071. __decorate([
  40072. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40073. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40074. __decorate([
  40075. BABYLON.serialize("useEmissiveAsIllumination")
  40076. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40077. __decorate([
  40078. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40079. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40080. __decorate([
  40081. BABYLON.serialize("linkEmissiveWithDiffuse")
  40082. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40083. __decorate([
  40084. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40085. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40086. __decorate([
  40087. BABYLON.serialize("useSpecularOverAlpha")
  40088. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40089. __decorate([
  40090. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40091. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40092. __decorate([
  40093. BABYLON.serialize("useReflectionOverAlpha")
  40094. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40095. __decorate([
  40096. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40097. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40098. __decorate([
  40099. BABYLON.serialize("disableLighting")
  40100. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40101. __decorate([
  40102. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40103. ], StandardMaterial.prototype, "disableLighting", void 0);
  40104. __decorate([
  40105. BABYLON.serialize("useObjectSpaceNormalMap")
  40106. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40107. __decorate([
  40108. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40109. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40110. __decorate([
  40111. BABYLON.serialize("useParallax")
  40112. ], StandardMaterial.prototype, "_useParallax", void 0);
  40113. __decorate([
  40114. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40115. ], StandardMaterial.prototype, "useParallax", void 0);
  40116. __decorate([
  40117. BABYLON.serialize("useParallaxOcclusion")
  40118. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40119. __decorate([
  40120. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40121. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40122. __decorate([
  40123. BABYLON.serialize()
  40124. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40125. __decorate([
  40126. BABYLON.serialize("roughness")
  40127. ], StandardMaterial.prototype, "_roughness", void 0);
  40128. __decorate([
  40129. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40130. ], StandardMaterial.prototype, "roughness", void 0);
  40131. __decorate([
  40132. BABYLON.serialize()
  40133. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40134. __decorate([
  40135. BABYLON.serialize()
  40136. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40137. __decorate([
  40138. BABYLON.serialize("useLightmapAsShadowmap")
  40139. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40140. __decorate([
  40141. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40142. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40143. __decorate([
  40144. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40145. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40146. __decorate([
  40147. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40148. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40149. __decorate([
  40150. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40151. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40152. __decorate([
  40153. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40154. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40155. __decorate([
  40156. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40157. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40158. __decorate([
  40159. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40160. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40161. __decorate([
  40162. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40163. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40164. __decorate([
  40165. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40166. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40167. __decorate([
  40168. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40169. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40170. __decorate([
  40171. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40172. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40173. __decorate([
  40174. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40175. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40176. __decorate([
  40177. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40178. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40179. __decorate([
  40180. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40181. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40182. __decorate([
  40183. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40184. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40185. __decorate([
  40186. BABYLON.serialize("maxSimultaneousLights")
  40187. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40188. __decorate([
  40189. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40190. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40191. __decorate([
  40192. BABYLON.serialize("invertNormalMapX")
  40193. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40194. __decorate([
  40195. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40196. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40197. __decorate([
  40198. BABYLON.serialize("invertNormalMapY")
  40199. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40200. __decorate([
  40201. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40202. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40203. __decorate([
  40204. BABYLON.serialize("twoSidedLighting")
  40205. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40206. __decorate([
  40207. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40208. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40209. __decorate([
  40210. BABYLON.serialize()
  40211. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40212. return StandardMaterial;
  40213. }(BABYLON.PushMaterial));
  40214. BABYLON.StandardMaterial = StandardMaterial;
  40215. })(BABYLON || (BABYLON = {}));
  40216. //# sourceMappingURL=babylon.standardMaterial.js.map
  40217. var BABYLON;
  40218. (function (BABYLON) {
  40219. /**
  40220. * Manages the defines for the PBR Material.
  40221. */
  40222. var PBRMaterialDefines = /** @class */ (function (_super) {
  40223. __extends(PBRMaterialDefines, _super);
  40224. /**
  40225. * Initializes the PBR Material defines.
  40226. */
  40227. function PBRMaterialDefines() {
  40228. var _this = _super.call(this) || this;
  40229. _this.PBR = true;
  40230. _this.MAINUV1 = false;
  40231. _this.MAINUV2 = false;
  40232. _this.UV1 = false;
  40233. _this.UV2 = false;
  40234. _this.ALBEDO = false;
  40235. _this.ALBEDODIRECTUV = 0;
  40236. _this.VERTEXCOLOR = false;
  40237. _this.AMBIENT = false;
  40238. _this.AMBIENTDIRECTUV = 0;
  40239. _this.AMBIENTINGRAYSCALE = false;
  40240. _this.OPACITY = false;
  40241. _this.VERTEXALPHA = false;
  40242. _this.OPACITYDIRECTUV = 0;
  40243. _this.OPACITYRGB = false;
  40244. _this.ALPHATEST = false;
  40245. _this.DEPTHPREPASS = false;
  40246. _this.ALPHABLEND = false;
  40247. _this.ALPHAFROMALBEDO = false;
  40248. _this.ALPHATESTVALUE = 0.5;
  40249. _this.SPECULAROVERALPHA = false;
  40250. _this.RADIANCEOVERALPHA = false;
  40251. _this.ALPHAFRESNEL = false;
  40252. _this.LINEARALPHAFRESNEL = false;
  40253. _this.PREMULTIPLYALPHA = false;
  40254. _this.EMISSIVE = false;
  40255. _this.EMISSIVEDIRECTUV = 0;
  40256. _this.REFLECTIVITY = false;
  40257. _this.REFLECTIVITYDIRECTUV = 0;
  40258. _this.SPECULARTERM = false;
  40259. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40260. _this.MICROSURFACEAUTOMATIC = false;
  40261. _this.LODBASEDMICROSFURACE = false;
  40262. _this.MICROSURFACEMAP = false;
  40263. _this.MICROSURFACEMAPDIRECTUV = 0;
  40264. _this.METALLICWORKFLOW = false;
  40265. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40266. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  40267. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  40268. _this.AOSTOREINMETALMAPRED = false;
  40269. _this.ENVIRONMENTBRDF = false;
  40270. _this.NORMAL = false;
  40271. _this.TANGENT = false;
  40272. _this.BUMP = false;
  40273. _this.BUMPDIRECTUV = 0;
  40274. _this.OBJECTSPACE_NORMALMAP = false;
  40275. _this.PARALLAX = false;
  40276. _this.PARALLAXOCCLUSION = false;
  40277. _this.NORMALXYSCALE = true;
  40278. _this.LIGHTMAP = false;
  40279. _this.LIGHTMAPDIRECTUV = 0;
  40280. _this.USELIGHTMAPASSHADOWMAP = false;
  40281. _this.REFLECTION = false;
  40282. _this.REFLECTIONMAP_3D = false;
  40283. _this.REFLECTIONMAP_SPHERICAL = false;
  40284. _this.REFLECTIONMAP_PLANAR = false;
  40285. _this.REFLECTIONMAP_CUBIC = false;
  40286. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40287. _this.REFLECTIONMAP_PROJECTION = false;
  40288. _this.REFLECTIONMAP_SKYBOX = false;
  40289. _this.REFLECTIONMAP_EXPLICIT = false;
  40290. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40291. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40292. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40293. _this.INVERTCUBICMAP = false;
  40294. _this.USESPHERICALFROMREFLECTIONMAP = false;
  40295. _this.USESPHERICALINVERTEX = false;
  40296. _this.REFLECTIONMAP_OPPOSITEZ = false;
  40297. _this.LODINREFLECTIONALPHA = false;
  40298. _this.GAMMAREFLECTION = false;
  40299. _this.RADIANCEOCCLUSION = false;
  40300. _this.HORIZONOCCLUSION = false;
  40301. _this.REFRACTION = false;
  40302. _this.REFRACTIONMAP_3D = false;
  40303. _this.REFRACTIONMAP_OPPOSITEZ = false;
  40304. _this.LODINREFRACTIONALPHA = false;
  40305. _this.GAMMAREFRACTION = false;
  40306. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  40307. _this.INSTANCES = false;
  40308. _this.NUM_BONE_INFLUENCERS = 0;
  40309. _this.BonesPerMesh = 0;
  40310. _this.NONUNIFORMSCALING = false;
  40311. _this.MORPHTARGETS = false;
  40312. _this.MORPHTARGETS_NORMAL = false;
  40313. _this.MORPHTARGETS_TANGENT = false;
  40314. _this.NUM_MORPH_INFLUENCERS = 0;
  40315. _this.IMAGEPROCESSING = false;
  40316. _this.VIGNETTE = false;
  40317. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  40318. _this.VIGNETTEBLENDMODEOPAQUE = false;
  40319. _this.TONEMAPPING = false;
  40320. _this.CONTRAST = false;
  40321. _this.COLORCURVES = false;
  40322. _this.COLORGRADING = false;
  40323. _this.COLORGRADING3D = false;
  40324. _this.SAMPLER3DGREENDEPTH = false;
  40325. _this.SAMPLER3DBGRMAP = false;
  40326. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  40327. _this.EXPOSURE = false;
  40328. _this.USEPHYSICALLIGHTFALLOFF = false;
  40329. _this.TWOSIDEDLIGHTING = false;
  40330. _this.SHADOWFLOAT = false;
  40331. _this.CLIPPLANE = false;
  40332. _this.POINTSIZE = false;
  40333. _this.FOG = false;
  40334. _this.LOGARITHMICDEPTH = false;
  40335. _this.FORCENORMALFORWARD = false;
  40336. _this.rebuild();
  40337. return _this;
  40338. }
  40339. /**
  40340. * Resets the PBR Material defines.
  40341. */
  40342. PBRMaterialDefines.prototype.reset = function () {
  40343. _super.prototype.reset.call(this);
  40344. this.ALPHATESTVALUE = 0.5;
  40345. this.PBR = true;
  40346. };
  40347. return PBRMaterialDefines;
  40348. }(BABYLON.MaterialDefines));
  40349. /**
  40350. * The Physically based material base class of BJS.
  40351. *
  40352. * This offers the main features of a standard PBR material.
  40353. * For more information, please refer to the documentation :
  40354. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  40355. */
  40356. var PBRBaseMaterial = /** @class */ (function (_super) {
  40357. __extends(PBRBaseMaterial, _super);
  40358. /**
  40359. * Instantiates a new PBRMaterial instance.
  40360. *
  40361. * @param name The material name
  40362. * @param scene The scene the material will be use in.
  40363. */
  40364. function PBRBaseMaterial(name, scene) {
  40365. var _this = _super.call(this, name, scene) || this;
  40366. /**
  40367. * Intensity of the direct lights e.g. the four lights available in your scene.
  40368. * This impacts both the direct diffuse and specular highlights.
  40369. */
  40370. _this._directIntensity = 1.0;
  40371. /**
  40372. * Intensity of the emissive part of the material.
  40373. * This helps controlling the emissive effect without modifying the emissive color.
  40374. */
  40375. _this._emissiveIntensity = 1.0;
  40376. /**
  40377. * Intensity of the environment e.g. how much the environment will light the object
  40378. * either through harmonics for rough material or through the refelction for shiny ones.
  40379. */
  40380. _this._environmentIntensity = 1.0;
  40381. /**
  40382. * This is a special control allowing the reduction of the specular highlights coming from the
  40383. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  40384. */
  40385. _this._specularIntensity = 1.0;
  40386. /**
  40387. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  40388. */
  40389. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  40390. /**
  40391. * Debug Control allowing disabling the bump map on this material.
  40392. */
  40393. _this._disableBumpMap = false;
  40394. /**
  40395. * AKA Occlusion Texture Intensity in other nomenclature.
  40396. */
  40397. _this._ambientTextureStrength = 1.0;
  40398. /**
  40399. * The color of a material in ambient lighting.
  40400. */
  40401. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  40402. /**
  40403. * AKA Diffuse Color in other nomenclature.
  40404. */
  40405. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  40406. /**
  40407. * AKA Specular Color in other nomenclature.
  40408. */
  40409. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  40410. /**
  40411. * The color applied when light is reflected from a material.
  40412. */
  40413. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  40414. /**
  40415. * The color applied when light is emitted from a material.
  40416. */
  40417. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  40418. /**
  40419. * AKA Glossiness in other nomenclature.
  40420. */
  40421. _this._microSurface = 0.9;
  40422. /**
  40423. * source material index of refraction (IOR)' / 'destination material IOR.
  40424. */
  40425. _this._indexOfRefraction = 0.66;
  40426. /**
  40427. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  40428. */
  40429. _this._invertRefractionY = false;
  40430. /**
  40431. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  40432. * Materials half opaque for instance using refraction could benefit from this control.
  40433. */
  40434. _this._linkRefractionWithTransparency = false;
  40435. /**
  40436. * Specifies that the material will use the light map as a show map.
  40437. */
  40438. _this._useLightmapAsShadowmap = false;
  40439. /**
  40440. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  40441. * makes the reflect vector face the model (under horizon).
  40442. */
  40443. _this._useHorizonOcclusion = true;
  40444. /**
  40445. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  40446. * too much the area relying on ambient texture to define their ambient occlusion.
  40447. */
  40448. _this._useRadianceOcclusion = true;
  40449. /**
  40450. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  40451. */
  40452. _this._useAlphaFromAlbedoTexture = false;
  40453. /**
  40454. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  40455. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  40456. */
  40457. _this._useSpecularOverAlpha = true;
  40458. /**
  40459. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  40460. */
  40461. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  40462. /**
  40463. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  40464. */
  40465. _this._useRoughnessFromMetallicTextureAlpha = true;
  40466. /**
  40467. * Specifies if the metallic texture contains the roughness information in its green channel.
  40468. */
  40469. _this._useRoughnessFromMetallicTextureGreen = false;
  40470. /**
  40471. * Specifies if the metallic texture contains the metallness information in its blue channel.
  40472. */
  40473. _this._useMetallnessFromMetallicTextureBlue = false;
  40474. /**
  40475. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  40476. */
  40477. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  40478. /**
  40479. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  40480. */
  40481. _this._useAmbientInGrayScale = false;
  40482. /**
  40483. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  40484. * The material will try to infer what glossiness each pixel should be.
  40485. */
  40486. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  40487. /**
  40488. * BJS is using an harcoded light falloff based on a manually sets up range.
  40489. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  40490. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  40491. */
  40492. _this._usePhysicalLightFalloff = true;
  40493. /**
  40494. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  40495. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  40496. */
  40497. _this._useRadianceOverAlpha = true;
  40498. /**
  40499. * Allows using an object space normal map (instead of tangent space).
  40500. */
  40501. _this._useObjectSpaceNormalMap = false;
  40502. /**
  40503. * Allows using the bump map in parallax mode.
  40504. */
  40505. _this._useParallax = false;
  40506. /**
  40507. * Allows using the bump map in parallax occlusion mode.
  40508. */
  40509. _this._useParallaxOcclusion = false;
  40510. /**
  40511. * Controls the scale bias of the parallax mode.
  40512. */
  40513. _this._parallaxScaleBias = 0.05;
  40514. /**
  40515. * If sets to true, disables all the lights affecting the material.
  40516. */
  40517. _this._disableLighting = false;
  40518. /**
  40519. * Number of Simultaneous lights allowed on the material.
  40520. */
  40521. _this._maxSimultaneousLights = 4;
  40522. /**
  40523. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  40524. */
  40525. _this._invertNormalMapX = false;
  40526. /**
  40527. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  40528. */
  40529. _this._invertNormalMapY = false;
  40530. /**
  40531. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  40532. */
  40533. _this._twoSidedLighting = false;
  40534. /**
  40535. * Defines the alpha limits in alpha test mode.
  40536. */
  40537. _this._alphaCutOff = 0.4;
  40538. /**
  40539. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  40540. */
  40541. _this._forceAlphaTest = false;
  40542. /**
  40543. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40544. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  40545. */
  40546. _this._useAlphaFresnel = false;
  40547. /**
  40548. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40549. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  40550. */
  40551. _this._useLinearAlphaFresnel = false;
  40552. /**
  40553. * The transparency mode of the material.
  40554. */
  40555. _this._transparencyMode = null;
  40556. /**
  40557. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  40558. * from cos thetav and roughness:
  40559. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  40560. */
  40561. _this._environmentBRDFTexture = null;
  40562. /**
  40563. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  40564. */
  40565. _this._forceIrradianceInFragment = false;
  40566. /**
  40567. * Force normal to face away from face.
  40568. */
  40569. _this._forceNormalForward = false;
  40570. /**
  40571. * Force metallic workflow.
  40572. */
  40573. _this._forceMetallicWorkflow = false;
  40574. /**
  40575. * Stores the available render targets.
  40576. */
  40577. _this._renderTargets = new BABYLON.SmartArray(16);
  40578. /**
  40579. * Sets the global ambient color for the material used in lighting calculations.
  40580. */
  40581. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  40582. // Setup the default processing configuration to the scene.
  40583. _this._attachImageProcessingConfiguration(null);
  40584. _this.getRenderTargetTextures = function () {
  40585. _this._renderTargets.reset();
  40586. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  40587. _this._renderTargets.push(_this._reflectionTexture);
  40588. }
  40589. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  40590. _this._renderTargets.push(_this._refractionTexture);
  40591. }
  40592. return _this._renderTargets;
  40593. };
  40594. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  40595. return _this;
  40596. }
  40597. /**
  40598. * Attaches a new image processing configuration to the PBR Material.
  40599. * @param configuration
  40600. */
  40601. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  40602. var _this = this;
  40603. if (configuration === this._imageProcessingConfiguration) {
  40604. return;
  40605. }
  40606. // Detaches observer.
  40607. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40608. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40609. }
  40610. // Pick the scene configuration if needed.
  40611. if (!configuration) {
  40612. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  40613. }
  40614. else {
  40615. this._imageProcessingConfiguration = configuration;
  40616. }
  40617. // Attaches observer.
  40618. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  40619. _this._markAllSubMeshesAsImageProcessingDirty();
  40620. });
  40621. };
  40622. /**
  40623. * Gets the name of the material class.
  40624. */
  40625. PBRBaseMaterial.prototype.getClassName = function () {
  40626. return "PBRBaseMaterial";
  40627. };
  40628. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  40629. /**
  40630. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40631. */
  40632. get: function () {
  40633. return this._useLogarithmicDepth;
  40634. },
  40635. /**
  40636. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40637. */
  40638. set: function (value) {
  40639. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  40640. },
  40641. enumerable: true,
  40642. configurable: true
  40643. });
  40644. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  40645. /**
  40646. * Gets the current transparency mode.
  40647. */
  40648. get: function () {
  40649. return this._transparencyMode;
  40650. },
  40651. /**
  40652. * Sets the transparency mode of the material.
  40653. */
  40654. set: function (value) {
  40655. if (this._transparencyMode === value) {
  40656. return;
  40657. }
  40658. this._transparencyMode = value;
  40659. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  40660. this._markAllSubMeshesAsTexturesAndMiscDirty();
  40661. },
  40662. enumerable: true,
  40663. configurable: true
  40664. });
  40665. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  40666. /**
  40667. * Returns true if alpha blending should be disabled.
  40668. */
  40669. get: function () {
  40670. return (this._linkRefractionWithTransparency ||
  40671. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  40672. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40673. },
  40674. enumerable: true,
  40675. configurable: true
  40676. });
  40677. /**
  40678. * Specifies whether or not this material should be rendered in alpha blend mode.
  40679. */
  40680. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  40681. if (this._disableAlphaBlending) {
  40682. return false;
  40683. }
  40684. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  40685. };
  40686. /**
  40687. * Specifies if the mesh will require alpha blending.
  40688. * @param mesh - BJS mesh.
  40689. */
  40690. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  40691. if (this._disableAlphaBlending) {
  40692. return false;
  40693. }
  40694. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  40695. };
  40696. /**
  40697. * Specifies whether or not this material should be rendered in alpha test mode.
  40698. */
  40699. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  40700. if (this._forceAlphaTest) {
  40701. return true;
  40702. }
  40703. if (this._linkRefractionWithTransparency) {
  40704. return false;
  40705. }
  40706. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40707. };
  40708. /**
  40709. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  40710. */
  40711. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  40712. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  40713. };
  40714. /**
  40715. * Gets the texture used for the alpha test.
  40716. */
  40717. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  40718. return this._albedoTexture;
  40719. };
  40720. /**
  40721. * Specifies that the submesh is ready to be used.
  40722. * @param mesh - BJS mesh.
  40723. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  40724. * @param useInstances - Specifies that instances should be used.
  40725. * @returns - boolean indicating that the submesh is ready or not.
  40726. */
  40727. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  40728. if (subMesh.effect && this.isFrozen) {
  40729. if (this._wasPreviouslyReady) {
  40730. return true;
  40731. }
  40732. }
  40733. if (!subMesh._materialDefines) {
  40734. subMesh._materialDefines = new PBRMaterialDefines();
  40735. }
  40736. var defines = subMesh._materialDefines;
  40737. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  40738. if (defines._renderId === this.getScene().getRenderId()) {
  40739. return true;
  40740. }
  40741. }
  40742. var scene = this.getScene();
  40743. var engine = scene.getEngine();
  40744. if (defines._areTexturesDirty) {
  40745. if (scene.texturesEnabled) {
  40746. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40747. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  40748. return false;
  40749. }
  40750. }
  40751. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40752. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  40753. return false;
  40754. }
  40755. }
  40756. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40757. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  40758. return false;
  40759. }
  40760. }
  40761. var reflectionTexture = this._getReflectionTexture();
  40762. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40763. if (!reflectionTexture.isReadyOrNotBlocking()) {
  40764. return false;
  40765. }
  40766. }
  40767. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40768. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  40769. return false;
  40770. }
  40771. }
  40772. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40773. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  40774. return false;
  40775. }
  40776. }
  40777. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40778. if (this._metallicTexture) {
  40779. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  40780. return false;
  40781. }
  40782. }
  40783. else if (this._reflectivityTexture) {
  40784. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  40785. return false;
  40786. }
  40787. }
  40788. if (this._microSurfaceTexture) {
  40789. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  40790. return false;
  40791. }
  40792. }
  40793. }
  40794. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40795. // Bump texture cannot be not blocking.
  40796. if (!this._bumpTexture.isReady()) {
  40797. return false;
  40798. }
  40799. }
  40800. var refractionTexture = this._getRefractionTexture();
  40801. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40802. if (!refractionTexture.isReadyOrNotBlocking()) {
  40803. return false;
  40804. }
  40805. }
  40806. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40807. // This is blocking.
  40808. if (!this._environmentBRDFTexture.isReady()) {
  40809. return false;
  40810. }
  40811. }
  40812. }
  40813. }
  40814. if (defines._areImageProcessingDirty) {
  40815. if (!this._imageProcessingConfiguration.isReady()) {
  40816. return false;
  40817. }
  40818. }
  40819. if (!engine.getCaps().standardDerivatives) {
  40820. var bufferMesh = null;
  40821. if (mesh.getClassName() === "InstancedMesh") {
  40822. bufferMesh = mesh.sourceMesh;
  40823. }
  40824. else if (mesh.getClassName() === "Mesh") {
  40825. bufferMesh = mesh;
  40826. }
  40827. if (bufferMesh && bufferMesh.geometry && bufferMesh.geometry.isReady() && !bufferMesh.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40828. bufferMesh.createNormals(true);
  40829. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  40830. }
  40831. }
  40832. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  40833. if (effect) {
  40834. scene.resetCachedMaterial();
  40835. subMesh.setEffect(effect, defines);
  40836. this.buildUniformLayout();
  40837. }
  40838. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40839. return false;
  40840. }
  40841. defines._renderId = scene.getRenderId();
  40842. this._wasPreviouslyReady = true;
  40843. return true;
  40844. };
  40845. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  40846. if (onCompiled === void 0) { onCompiled = null; }
  40847. if (onError === void 0) { onError = null; }
  40848. if (useInstances === void 0) { useInstances = null; }
  40849. if (useClipPlane === void 0) { useClipPlane = null; }
  40850. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  40851. if (!defines.isDirty) {
  40852. return null;
  40853. }
  40854. defines.markAsProcessed();
  40855. var scene = this.getScene();
  40856. var engine = scene.getEngine();
  40857. // Fallbacks
  40858. var fallbacks = new BABYLON.EffectFallbacks();
  40859. var fallbackRank = 0;
  40860. if (defines.USESPHERICALINVERTEX) {
  40861. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  40862. }
  40863. if (defines.FOG) {
  40864. fallbacks.addFallback(fallbackRank, "FOG");
  40865. }
  40866. if (defines.POINTSIZE) {
  40867. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  40868. }
  40869. if (defines.LOGARITHMICDEPTH) {
  40870. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  40871. }
  40872. if (defines.PARALLAX) {
  40873. fallbacks.addFallback(fallbackRank, "PARALLAX");
  40874. }
  40875. if (defines.PARALLAXOCCLUSION) {
  40876. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  40877. }
  40878. if (defines.ENVIRONMENTBRDF) {
  40879. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  40880. }
  40881. if (defines.TANGENT) {
  40882. fallbacks.addFallback(fallbackRank++, "TANGENT");
  40883. }
  40884. if (defines.BUMP) {
  40885. fallbacks.addFallback(fallbackRank++, "BUMP");
  40886. }
  40887. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  40888. if (defines.SPECULARTERM) {
  40889. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  40890. }
  40891. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  40892. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  40893. }
  40894. if (defines.LIGHTMAP) {
  40895. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  40896. }
  40897. if (defines.NORMAL) {
  40898. fallbacks.addFallback(fallbackRank++, "NORMAL");
  40899. }
  40900. if (defines.AMBIENT) {
  40901. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  40902. }
  40903. if (defines.EMISSIVE) {
  40904. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  40905. }
  40906. if (defines.VERTEXCOLOR) {
  40907. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  40908. }
  40909. if (defines.NUM_BONE_INFLUENCERS > 0) {
  40910. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  40911. }
  40912. if (defines.MORPHTARGETS) {
  40913. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  40914. }
  40915. //Attributes
  40916. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40917. if (defines.NORMAL) {
  40918. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40919. }
  40920. if (defines.TANGENT) {
  40921. attribs.push(BABYLON.VertexBuffer.TangentKind);
  40922. }
  40923. if (defines.UV1) {
  40924. attribs.push(BABYLON.VertexBuffer.UVKind);
  40925. }
  40926. if (defines.UV2) {
  40927. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40928. }
  40929. if (defines.VERTEXCOLOR) {
  40930. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40931. }
  40932. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40933. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40934. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40935. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  40936. "vFogInfos", "vFogColor", "pointSize",
  40937. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  40938. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40939. "mBones",
  40940. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  40941. "vLightingIntensity",
  40942. "logarithmicDepthConstant",
  40943. "vSphericalX", "vSphericalY", "vSphericalZ",
  40944. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  40945. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  40946. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  40947. "vTangentSpaceParams"
  40948. ];
  40949. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  40950. "bumpSampler", "lightmapSampler", "opacitySampler",
  40951. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  40952. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  40953. "microSurfaceSampler", "environmentBrdfSampler"];
  40954. var uniformBuffers = ["Material", "Scene"];
  40955. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40956. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40957. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40958. uniformsNames: uniforms,
  40959. uniformBuffersNames: uniformBuffers,
  40960. samplers: samplers,
  40961. defines: defines,
  40962. maxSimultaneousLights: this._maxSimultaneousLights
  40963. });
  40964. var join = defines.toString();
  40965. return engine.createEffect("pbr", {
  40966. attributes: attribs,
  40967. uniformsNames: uniforms,
  40968. uniformBuffersNames: uniformBuffers,
  40969. samplers: samplers,
  40970. defines: join,
  40971. fallbacks: fallbacks,
  40972. onCompiled: onCompiled,
  40973. onError: onError,
  40974. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40975. }, engine);
  40976. };
  40977. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  40978. if (useInstances === void 0) { useInstances = null; }
  40979. if (useClipPlane === void 0) { useClipPlane = null; }
  40980. var scene = this.getScene();
  40981. var engine = scene.getEngine();
  40982. // Lights
  40983. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  40984. defines._needNormals = true;
  40985. // Textures
  40986. if (defines._areTexturesDirty) {
  40987. defines._needUVs = false;
  40988. if (scene.texturesEnabled) {
  40989. if (scene.getEngine().getCaps().textureLOD) {
  40990. defines.LODBASEDMICROSFURACE = true;
  40991. }
  40992. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40993. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  40994. }
  40995. else {
  40996. defines.ALBEDO = false;
  40997. }
  40998. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40999. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41000. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  41001. }
  41002. else {
  41003. defines.AMBIENT = false;
  41004. }
  41005. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41006. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41007. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41008. }
  41009. else {
  41010. defines.OPACITY = false;
  41011. }
  41012. var reflectionTexture = this._getReflectionTexture();
  41013. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41014. defines.REFLECTION = true;
  41015. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  41016. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  41017. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  41018. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  41019. defines.INVERTCUBICMAP = true;
  41020. }
  41021. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  41022. switch (reflectionTexture.coordinatesMode) {
  41023. case BABYLON.Texture.CUBIC_MODE:
  41024. case BABYLON.Texture.INVCUBIC_MODE:
  41025. defines.REFLECTIONMAP_CUBIC = true;
  41026. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  41027. break;
  41028. case BABYLON.Texture.EXPLICIT_MODE:
  41029. defines.REFLECTIONMAP_EXPLICIT = true;
  41030. break;
  41031. case BABYLON.Texture.PLANAR_MODE:
  41032. defines.REFLECTIONMAP_PLANAR = true;
  41033. break;
  41034. case BABYLON.Texture.PROJECTION_MODE:
  41035. defines.REFLECTIONMAP_PROJECTION = true;
  41036. break;
  41037. case BABYLON.Texture.SKYBOX_MODE:
  41038. defines.REFLECTIONMAP_SKYBOX = true;
  41039. break;
  41040. case BABYLON.Texture.SPHERICAL_MODE:
  41041. defines.REFLECTIONMAP_SPHERICAL = true;
  41042. break;
  41043. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41044. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  41045. break;
  41046. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41047. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  41048. break;
  41049. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41050. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  41051. break;
  41052. }
  41053. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  41054. if (reflectionTexture.sphericalPolynomial) {
  41055. defines.USESPHERICALFROMREFLECTIONMAP = true;
  41056. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  41057. defines.USESPHERICALINVERTEX = false;
  41058. }
  41059. else {
  41060. defines.USESPHERICALINVERTEX = true;
  41061. }
  41062. }
  41063. }
  41064. }
  41065. else {
  41066. defines.REFLECTION = false;
  41067. defines.REFLECTIONMAP_3D = false;
  41068. defines.REFLECTIONMAP_SPHERICAL = false;
  41069. defines.REFLECTIONMAP_PLANAR = false;
  41070. defines.REFLECTIONMAP_CUBIC = false;
  41071. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41072. defines.REFLECTIONMAP_PROJECTION = false;
  41073. defines.REFLECTIONMAP_SKYBOX = false;
  41074. defines.REFLECTIONMAP_EXPLICIT = false;
  41075. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41076. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41077. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41078. defines.INVERTCUBICMAP = false;
  41079. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41080. defines.USESPHERICALINVERTEX = false;
  41081. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41082. defines.LODINREFLECTIONALPHA = false;
  41083. defines.GAMMAREFLECTION = false;
  41084. }
  41085. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41086. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41087. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41088. }
  41089. else {
  41090. defines.LIGHTMAP = false;
  41091. }
  41092. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41093. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41094. }
  41095. else {
  41096. defines.EMISSIVE = false;
  41097. }
  41098. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41099. if (this._metallicTexture) {
  41100. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41101. defines.METALLICWORKFLOW = true;
  41102. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41103. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41104. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41105. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41106. }
  41107. else if (this._reflectivityTexture) {
  41108. defines.METALLICWORKFLOW = false;
  41109. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41110. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41111. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41112. }
  41113. else {
  41114. defines.METALLICWORKFLOW = false;
  41115. defines.REFLECTIVITY = false;
  41116. }
  41117. if (this._microSurfaceTexture) {
  41118. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41119. }
  41120. else {
  41121. defines.MICROSURFACEMAP = false;
  41122. }
  41123. }
  41124. else {
  41125. defines.REFLECTIVITY = false;
  41126. defines.MICROSURFACEMAP = false;
  41127. }
  41128. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41129. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41130. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41131. defines.PARALLAX = true;
  41132. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41133. }
  41134. else {
  41135. defines.PARALLAX = false;
  41136. }
  41137. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41138. }
  41139. else {
  41140. defines.BUMP = false;
  41141. }
  41142. var refractionTexture = this._getRefractionTexture();
  41143. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41144. defines.REFRACTION = true;
  41145. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41146. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41147. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41148. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41149. if (this._linkRefractionWithTransparency) {
  41150. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41151. }
  41152. }
  41153. else {
  41154. defines.REFRACTION = false;
  41155. }
  41156. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41157. defines.ENVIRONMENTBRDF = true;
  41158. }
  41159. else {
  41160. defines.ENVIRONMENTBRDF = false;
  41161. }
  41162. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41163. defines.ALPHAFROMALBEDO = true;
  41164. }
  41165. else {
  41166. defines.ALPHAFROMALBEDO = false;
  41167. }
  41168. }
  41169. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41170. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41171. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41172. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  41173. defines.METALLICWORKFLOW = true;
  41174. }
  41175. else {
  41176. defines.METALLICWORKFLOW = false;
  41177. }
  41178. if (!this.backFaceCulling && this._twoSidedLighting) {
  41179. defines.TWOSIDEDLIGHTING = true;
  41180. }
  41181. else {
  41182. defines.TWOSIDEDLIGHTING = false;
  41183. }
  41184. defines.ALPHATESTVALUE = this._alphaCutOff;
  41185. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41186. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41187. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41188. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41189. }
  41190. if (defines._areImageProcessingDirty) {
  41191. this._imageProcessingConfiguration.prepareDefines(defines);
  41192. }
  41193. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41194. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41195. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41196. // Misc.
  41197. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41198. // Values that need to be evaluated on every frame
  41199. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41200. // Attribs
  41201. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41202. };
  41203. /**
  41204. * Force shader compilation
  41205. */
  41206. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41207. var _this = this;
  41208. var localOptions = __assign({ clipPlane: false }, options);
  41209. var defines = new PBRMaterialDefines();
  41210. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41211. if (effect.isReady()) {
  41212. if (onCompiled) {
  41213. onCompiled(this);
  41214. }
  41215. }
  41216. else {
  41217. effect.onCompileObservable.add(function () {
  41218. if (onCompiled) {
  41219. onCompiled(_this);
  41220. }
  41221. });
  41222. }
  41223. };
  41224. /**
  41225. * Initializes the uniform buffer layout for the shader.
  41226. */
  41227. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41228. // Order is important !
  41229. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41230. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41231. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41232. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41233. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41234. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41235. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41236. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41237. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41238. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41239. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41240. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41241. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41242. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41243. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41244. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41245. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41246. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41247. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41248. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41249. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41250. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41251. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41252. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41253. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41254. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41255. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41256. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41257. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41258. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41259. this._uniformBuffer.addUniform("pointSize", 1);
  41260. this._uniformBuffer.create();
  41261. };
  41262. /**
  41263. * Unbinds the textures.
  41264. */
  41265. PBRBaseMaterial.prototype.unbind = function () {
  41266. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41267. this._uniformBuffer.setTexture("reflectionSampler", null);
  41268. }
  41269. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41270. this._uniformBuffer.setTexture("refractionSampler", null);
  41271. }
  41272. _super.prototype.unbind.call(this);
  41273. };
  41274. /**
  41275. * Binds the submesh data.
  41276. * @param world - The world matrix.
  41277. * @param mesh - The BJS mesh.
  41278. * @param subMesh - A submesh of the BJS mesh.
  41279. */
  41280. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41281. var scene = this.getScene();
  41282. var defines = subMesh._materialDefines;
  41283. if (!defines) {
  41284. return;
  41285. }
  41286. var effect = subMesh.effect;
  41287. if (!effect) {
  41288. return;
  41289. }
  41290. this._activeEffect = effect;
  41291. // Matrices
  41292. this.bindOnlyWorldMatrix(world);
  41293. // Normal Matrix
  41294. if (defines.OBJECTSPACE_NORMALMAP) {
  41295. world.toNormalMatrix(this._normalMatrix);
  41296. this.bindOnlyNormalMatrix(this._normalMatrix);
  41297. }
  41298. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41299. // Bones
  41300. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  41301. var reflectionTexture = null;
  41302. if (mustRebind) {
  41303. this._uniformBuffer.bindToEffect(effect, "Material");
  41304. this.bindViewProjection(effect);
  41305. reflectionTexture = this._getReflectionTexture();
  41306. var refractionTexture = this._getRefractionTexture();
  41307. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41308. // Texture uniforms
  41309. if (scene.texturesEnabled) {
  41310. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41311. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  41312. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  41313. }
  41314. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41315. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  41316. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41317. }
  41318. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41319. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41320. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  41321. }
  41322. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41323. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  41324. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  41325. if (reflectionTexture.boundingBoxSize) {
  41326. var cubeTexture = reflectionTexture;
  41327. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  41328. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  41329. }
  41330. var polynomials = reflectionTexture.sphericalPolynomial;
  41331. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  41332. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  41333. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  41334. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  41335. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  41336. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  41337. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  41338. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  41339. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  41340. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  41341. }
  41342. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  41343. }
  41344. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41345. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  41346. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  41347. }
  41348. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41349. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  41350. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  41351. }
  41352. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41353. if (this._metallicTexture) {
  41354. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  41355. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  41356. }
  41357. else if (this._reflectivityTexture) {
  41358. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  41359. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  41360. }
  41361. if (this._microSurfaceTexture) {
  41362. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  41363. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  41364. }
  41365. }
  41366. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41367. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  41368. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  41369. if (scene._mirroredCameraPosition) {
  41370. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  41371. }
  41372. else {
  41373. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  41374. }
  41375. }
  41376. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41377. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  41378. var depth = 1.0;
  41379. if (!refractionTexture.isCube) {
  41380. if (refractionTexture.depth) {
  41381. depth = refractionTexture.depth;
  41382. }
  41383. }
  41384. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  41385. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  41386. }
  41387. }
  41388. // Point size
  41389. if (this.pointsCloud) {
  41390. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  41391. }
  41392. // Colors
  41393. if (defines.METALLICWORKFLOW) {
  41394. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  41395. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  41396. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  41397. }
  41398. else {
  41399. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  41400. }
  41401. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  41402. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  41403. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  41404. // Misc
  41405. this._lightingInfos.x = this._directIntensity;
  41406. this._lightingInfos.y = this._emissiveIntensity;
  41407. this._lightingInfos.z = this._environmentIntensity;
  41408. this._lightingInfos.w = this._specularIntensity;
  41409. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  41410. }
  41411. // Textures
  41412. if (scene.texturesEnabled) {
  41413. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41414. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  41415. }
  41416. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41417. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  41418. }
  41419. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41420. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  41421. }
  41422. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41423. if (defines.LODBASEDMICROSFURACE) {
  41424. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  41425. }
  41426. else {
  41427. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  41428. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  41429. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  41430. }
  41431. }
  41432. if (defines.ENVIRONMENTBRDF) {
  41433. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  41434. }
  41435. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41436. if (defines.LODBASEDMICROSFURACE) {
  41437. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  41438. }
  41439. else {
  41440. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  41441. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  41442. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  41443. }
  41444. }
  41445. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41446. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  41447. }
  41448. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41449. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  41450. }
  41451. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41452. if (this._metallicTexture) {
  41453. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  41454. }
  41455. else if (this._reflectivityTexture) {
  41456. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  41457. }
  41458. if (this._microSurfaceTexture) {
  41459. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  41460. }
  41461. }
  41462. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41463. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  41464. }
  41465. }
  41466. // Clip plane
  41467. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  41468. // Colors
  41469. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  41470. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41471. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  41472. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  41473. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  41474. }
  41475. if (mustRebind || !this.isFrozen) {
  41476. // Lights
  41477. if (scene.lightsEnabled && !this._disableLighting) {
  41478. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  41479. }
  41480. // View
  41481. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  41482. this.bindView(effect);
  41483. }
  41484. // Fog
  41485. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  41486. // Morph targets
  41487. if (defines.NUM_MORPH_INFLUENCERS) {
  41488. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  41489. }
  41490. // image processing
  41491. this._imageProcessingConfiguration.bind(this._activeEffect);
  41492. // Log. depth
  41493. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  41494. }
  41495. this._uniformBuffer.update();
  41496. this._afterBind(mesh);
  41497. };
  41498. /**
  41499. * Returns the animatable textures.
  41500. * @returns - Array of animatable textures.
  41501. */
  41502. PBRBaseMaterial.prototype.getAnimatables = function () {
  41503. var results = [];
  41504. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  41505. results.push(this._albedoTexture);
  41506. }
  41507. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  41508. results.push(this._ambientTexture);
  41509. }
  41510. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  41511. results.push(this._opacityTexture);
  41512. }
  41513. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  41514. results.push(this._reflectionTexture);
  41515. }
  41516. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  41517. results.push(this._emissiveTexture);
  41518. }
  41519. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  41520. results.push(this._metallicTexture);
  41521. }
  41522. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  41523. results.push(this._reflectivityTexture);
  41524. }
  41525. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  41526. results.push(this._bumpTexture);
  41527. }
  41528. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  41529. results.push(this._lightmapTexture);
  41530. }
  41531. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  41532. results.push(this._refractionTexture);
  41533. }
  41534. return results;
  41535. };
  41536. /**
  41537. * Returns the texture used for reflections.
  41538. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  41539. */
  41540. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  41541. if (this._reflectionTexture) {
  41542. return this._reflectionTexture;
  41543. }
  41544. return this.getScene().environmentTexture;
  41545. };
  41546. /**
  41547. * Returns the texture used for refraction or null if none is used.
  41548. * @returns - Refection texture if present. If no refraction texture and refraction
  41549. * is linked with transparency, returns environment texture. Otherwise, returns null.
  41550. */
  41551. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  41552. if (this._refractionTexture) {
  41553. return this._refractionTexture;
  41554. }
  41555. if (this._linkRefractionWithTransparency) {
  41556. return this.getScene().environmentTexture;
  41557. }
  41558. return null;
  41559. };
  41560. /**
  41561. * Disposes the resources of the material.
  41562. * @param forceDisposeEffect - Forces the disposal of effects.
  41563. * @param forceDisposeTextures - Forces the disposal of all textures.
  41564. */
  41565. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41566. if (forceDisposeTextures) {
  41567. if (this._albedoTexture) {
  41568. this._albedoTexture.dispose();
  41569. }
  41570. if (this._ambientTexture) {
  41571. this._ambientTexture.dispose();
  41572. }
  41573. if (this._opacityTexture) {
  41574. this._opacityTexture.dispose();
  41575. }
  41576. if (this._reflectionTexture) {
  41577. this._reflectionTexture.dispose();
  41578. }
  41579. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  41580. this._environmentBRDFTexture.dispose();
  41581. }
  41582. if (this._emissiveTexture) {
  41583. this._emissiveTexture.dispose();
  41584. }
  41585. if (this._metallicTexture) {
  41586. this._metallicTexture.dispose();
  41587. }
  41588. if (this._reflectivityTexture) {
  41589. this._reflectivityTexture.dispose();
  41590. }
  41591. if (this._bumpTexture) {
  41592. this._bumpTexture.dispose();
  41593. }
  41594. if (this._lightmapTexture) {
  41595. this._lightmapTexture.dispose();
  41596. }
  41597. if (this._refractionTexture) {
  41598. this._refractionTexture.dispose();
  41599. }
  41600. }
  41601. this._renderTargets.dispose();
  41602. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41603. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41604. }
  41605. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41606. };
  41607. /**
  41608. * Stores the reflectivity values based on metallic roughness workflow.
  41609. */
  41610. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  41611. __decorate([
  41612. BABYLON.serializeAsImageProcessingConfiguration()
  41613. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  41614. __decorate([
  41615. BABYLON.serialize()
  41616. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  41617. __decorate([
  41618. BABYLON.serialize()
  41619. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  41620. return PBRBaseMaterial;
  41621. }(BABYLON.PushMaterial));
  41622. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  41623. })(BABYLON || (BABYLON = {}));
  41624. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  41625. var BABYLON;
  41626. (function (BABYLON) {
  41627. /**
  41628. * The Physically based simple base material of BJS.
  41629. *
  41630. * This enables better naming and convention enforcements on top of the pbrMaterial.
  41631. * It is used as the base class for both the specGloss and metalRough conventions.
  41632. */
  41633. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  41634. __extends(PBRBaseSimpleMaterial, _super);
  41635. /**
  41636. * Instantiates a new PBRMaterial instance.
  41637. *
  41638. * @param name The material name
  41639. * @param scene The scene the material will be use in.
  41640. */
  41641. function PBRBaseSimpleMaterial(name, scene) {
  41642. var _this = _super.call(this, name, scene) || this;
  41643. /**
  41644. * Number of Simultaneous lights allowed on the material.
  41645. */
  41646. _this.maxSimultaneousLights = 4;
  41647. /**
  41648. * If sets to true, disables all the lights affecting the material.
  41649. */
  41650. _this.disableLighting = false;
  41651. /**
  41652. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41653. */
  41654. _this.invertNormalMapX = false;
  41655. /**
  41656. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41657. */
  41658. _this.invertNormalMapY = false;
  41659. /**
  41660. * Emissivie color used to self-illuminate the model.
  41661. */
  41662. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41663. /**
  41664. * Occlusion Channel Strenght.
  41665. */
  41666. _this.occlusionStrength = 1.0;
  41667. _this.useLightmapAsShadowmap = false;
  41668. _this._useAlphaFromAlbedoTexture = true;
  41669. _this._useAmbientInGrayScale = true;
  41670. return _this;
  41671. }
  41672. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  41673. /**
  41674. * Gets the current double sided mode.
  41675. */
  41676. get: function () {
  41677. return this._twoSidedLighting;
  41678. },
  41679. /**
  41680. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41681. */
  41682. set: function (value) {
  41683. if (this._twoSidedLighting === value) {
  41684. return;
  41685. }
  41686. this._twoSidedLighting = value;
  41687. this.backFaceCulling = !value;
  41688. this._markAllSubMeshesAsTexturesDirty();
  41689. },
  41690. enumerable: true,
  41691. configurable: true
  41692. });
  41693. /**
  41694. * Return the active textures of the material.
  41695. */
  41696. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  41697. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41698. if (this.environmentTexture) {
  41699. activeTextures.push(this.environmentTexture);
  41700. }
  41701. if (this.normalTexture) {
  41702. activeTextures.push(this.normalTexture);
  41703. }
  41704. if (this.emissiveTexture) {
  41705. activeTextures.push(this.emissiveTexture);
  41706. }
  41707. if (this.occlusionTexture) {
  41708. activeTextures.push(this.occlusionTexture);
  41709. }
  41710. if (this.lightmapTexture) {
  41711. activeTextures.push(this.lightmapTexture);
  41712. }
  41713. return activeTextures;
  41714. };
  41715. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  41716. if (_super.prototype.hasTexture.call(this, texture)) {
  41717. return true;
  41718. }
  41719. if (this.lightmapTexture === texture) {
  41720. return true;
  41721. }
  41722. return false;
  41723. };
  41724. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  41725. return "PBRBaseSimpleMaterial";
  41726. };
  41727. __decorate([
  41728. BABYLON.serialize(),
  41729. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41730. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  41731. __decorate([
  41732. BABYLON.serialize(),
  41733. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41734. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  41735. __decorate([
  41736. BABYLON.serializeAsTexture(),
  41737. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  41738. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  41739. __decorate([
  41740. BABYLON.serialize(),
  41741. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41742. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  41743. __decorate([
  41744. BABYLON.serialize(),
  41745. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41746. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  41747. __decorate([
  41748. BABYLON.serializeAsTexture(),
  41749. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  41750. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  41751. __decorate([
  41752. BABYLON.serializeAsColor3("emissive"),
  41753. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41754. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  41755. __decorate([
  41756. BABYLON.serializeAsTexture(),
  41757. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41758. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  41759. __decorate([
  41760. BABYLON.serialize(),
  41761. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  41762. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  41763. __decorate([
  41764. BABYLON.serializeAsTexture(),
  41765. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  41766. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  41767. __decorate([
  41768. BABYLON.serialize(),
  41769. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  41770. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  41771. __decorate([
  41772. BABYLON.serialize()
  41773. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  41774. __decorate([
  41775. BABYLON.serializeAsTexture(),
  41776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41777. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  41778. __decorate([
  41779. BABYLON.serialize(),
  41780. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41781. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41782. return PBRBaseSimpleMaterial;
  41783. }(BABYLON.PBRBaseMaterial));
  41784. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  41785. })(BABYLON || (BABYLON = {}));
  41786. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  41787. var BABYLON;
  41788. (function (BABYLON) {
  41789. /**
  41790. * The Physically based material of BJS.
  41791. *
  41792. * This offers the main features of a standard PBR material.
  41793. * For more information, please refer to the documentation :
  41794. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41795. */
  41796. var PBRMaterial = /** @class */ (function (_super) {
  41797. __extends(PBRMaterial, _super);
  41798. /**
  41799. * Instantiates a new PBRMaterial instance.
  41800. *
  41801. * @param name The material name
  41802. * @param scene The scene the material will be use in.
  41803. */
  41804. function PBRMaterial(name, scene) {
  41805. var _this = _super.call(this, name, scene) || this;
  41806. /**
  41807. * Intensity of the direct lights e.g. the four lights available in your scene.
  41808. * This impacts both the direct diffuse and specular highlights.
  41809. */
  41810. _this.directIntensity = 1.0;
  41811. /**
  41812. * Intensity of the emissive part of the material.
  41813. * This helps controlling the emissive effect without modifying the emissive color.
  41814. */
  41815. _this.emissiveIntensity = 1.0;
  41816. /**
  41817. * Intensity of the environment e.g. how much the environment will light the object
  41818. * either through harmonics for rough material or through the refelction for shiny ones.
  41819. */
  41820. _this.environmentIntensity = 1.0;
  41821. /**
  41822. * This is a special control allowing the reduction of the specular highlights coming from the
  41823. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41824. */
  41825. _this.specularIntensity = 1.0;
  41826. /**
  41827. * Debug Control allowing disabling the bump map on this material.
  41828. */
  41829. _this.disableBumpMap = false;
  41830. /**
  41831. * AKA Occlusion Texture Intensity in other nomenclature.
  41832. */
  41833. _this.ambientTextureStrength = 1.0;
  41834. /**
  41835. * The color of a material in ambient lighting.
  41836. */
  41837. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41838. /**
  41839. * AKA Diffuse Color in other nomenclature.
  41840. */
  41841. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  41842. /**
  41843. * AKA Specular Color in other nomenclature.
  41844. */
  41845. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41846. /**
  41847. * The color reflected from the material.
  41848. */
  41849. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  41850. /**
  41851. * The color emitted from the material.
  41852. */
  41853. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41854. /**
  41855. * AKA Glossiness in other nomenclature.
  41856. */
  41857. _this.microSurface = 1.0;
  41858. /**
  41859. * source material index of refraction (IOR)' / 'destination material IOR.
  41860. */
  41861. _this.indexOfRefraction = 0.66;
  41862. /**
  41863. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41864. */
  41865. _this.invertRefractionY = false;
  41866. /**
  41867. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41868. * Materials half opaque for instance using refraction could benefit from this control.
  41869. */
  41870. _this.linkRefractionWithTransparency = false;
  41871. _this.useLightmapAsShadowmap = false;
  41872. /**
  41873. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41874. */
  41875. _this.useAlphaFromAlbedoTexture = false;
  41876. /**
  41877. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41878. */
  41879. _this.forceAlphaTest = false;
  41880. /**
  41881. * Defines the alpha limits in alpha test mode.
  41882. */
  41883. _this.alphaCutOff = 0.4;
  41884. /**
  41885. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41886. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41887. */
  41888. _this.useSpecularOverAlpha = true;
  41889. /**
  41890. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41891. */
  41892. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  41893. /**
  41894. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41895. */
  41896. _this.useRoughnessFromMetallicTextureAlpha = true;
  41897. /**
  41898. * Specifies if the metallic texture contains the roughness information in its green channel.
  41899. */
  41900. _this.useRoughnessFromMetallicTextureGreen = false;
  41901. /**
  41902. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41903. */
  41904. _this.useMetallnessFromMetallicTextureBlue = false;
  41905. /**
  41906. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41907. */
  41908. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  41909. /**
  41910. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41911. */
  41912. _this.useAmbientInGrayScale = false;
  41913. /**
  41914. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41915. * The material will try to infer what glossiness each pixel should be.
  41916. */
  41917. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  41918. /**
  41919. * BJS is using an harcoded light falloff based on a manually sets up range.
  41920. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41921. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41922. */
  41923. _this.usePhysicalLightFalloff = true;
  41924. /**
  41925. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41926. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41927. */
  41928. _this.useRadianceOverAlpha = true;
  41929. /**
  41930. * Allows using an object space normal map (instead of tangent space).
  41931. */
  41932. _this.useObjectSpaceNormalMap = false;
  41933. /**
  41934. * Allows using the bump map in parallax mode.
  41935. */
  41936. _this.useParallax = false;
  41937. /**
  41938. * Allows using the bump map in parallax occlusion mode.
  41939. */
  41940. _this.useParallaxOcclusion = false;
  41941. /**
  41942. * Controls the scale bias of the parallax mode.
  41943. */
  41944. _this.parallaxScaleBias = 0.05;
  41945. /**
  41946. * If sets to true, disables all the lights affecting the material.
  41947. */
  41948. _this.disableLighting = false;
  41949. /**
  41950. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41951. */
  41952. _this.forceIrradianceInFragment = false;
  41953. /**
  41954. * Number of Simultaneous lights allowed on the material.
  41955. */
  41956. _this.maxSimultaneousLights = 4;
  41957. /**
  41958. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41959. */
  41960. _this.invertNormalMapX = false;
  41961. /**
  41962. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41963. */
  41964. _this.invertNormalMapY = false;
  41965. /**
  41966. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41967. */
  41968. _this.twoSidedLighting = false;
  41969. /**
  41970. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41971. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41972. */
  41973. _this.useAlphaFresnel = false;
  41974. /**
  41975. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41976. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41977. */
  41978. _this.useLinearAlphaFresnel = false;
  41979. /**
  41980. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41981. * And/Or occlude the blended part.
  41982. */
  41983. _this.environmentBRDFTexture = null;
  41984. /**
  41985. * Force normal to face away from face.
  41986. */
  41987. _this.forceNormalForward = false;
  41988. /**
  41989. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41990. * makes the reflect vector face the model (under horizon).
  41991. */
  41992. _this.useHorizonOcclusion = true;
  41993. /**
  41994. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41995. * too much the area relying on ambient texture to define their ambient occlusion.
  41996. */
  41997. _this.useRadianceOcclusion = true;
  41998. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41999. return _this;
  42000. }
  42001. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  42002. /**
  42003. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  42004. */
  42005. get: function () {
  42006. return this._PBRMATERIAL_OPAQUE;
  42007. },
  42008. enumerable: true,
  42009. configurable: true
  42010. });
  42011. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  42012. /**
  42013. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42014. */
  42015. get: function () {
  42016. return this._PBRMATERIAL_ALPHATEST;
  42017. },
  42018. enumerable: true,
  42019. configurable: true
  42020. });
  42021. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  42022. /**
  42023. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42024. */
  42025. get: function () {
  42026. return this._PBRMATERIAL_ALPHABLEND;
  42027. },
  42028. enumerable: true,
  42029. configurable: true
  42030. });
  42031. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  42032. /**
  42033. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42034. * They are also discarded below the alpha cutoff threshold to improve performances.
  42035. */
  42036. get: function () {
  42037. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  42038. },
  42039. enumerable: true,
  42040. configurable: true
  42041. });
  42042. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  42043. /**
  42044. * Gets the image processing configuration used either in this material.
  42045. */
  42046. get: function () {
  42047. return this._imageProcessingConfiguration;
  42048. },
  42049. /**
  42050. * Sets the Default image processing configuration used either in the this material.
  42051. *
  42052. * If sets to null, the scene one is in use.
  42053. */
  42054. set: function (value) {
  42055. this._attachImageProcessingConfiguration(value);
  42056. // Ensure the effect will be rebuilt.
  42057. this._markAllSubMeshesAsTexturesDirty();
  42058. },
  42059. enumerable: true,
  42060. configurable: true
  42061. });
  42062. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  42063. /**
  42064. * Gets wether the color curves effect is enabled.
  42065. */
  42066. get: function () {
  42067. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42068. },
  42069. /**
  42070. * Sets wether the color curves effect is enabled.
  42071. */
  42072. set: function (value) {
  42073. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42074. },
  42075. enumerable: true,
  42076. configurable: true
  42077. });
  42078. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42079. /**
  42080. * Gets wether the color grading effect is enabled.
  42081. */
  42082. get: function () {
  42083. return this.imageProcessingConfiguration.colorGradingEnabled;
  42084. },
  42085. /**
  42086. * Gets wether the color grading effect is enabled.
  42087. */
  42088. set: function (value) {
  42089. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42090. },
  42091. enumerable: true,
  42092. configurable: true
  42093. });
  42094. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42095. /**
  42096. * Gets wether tonemapping is enabled or not.
  42097. */
  42098. get: function () {
  42099. return this._imageProcessingConfiguration.toneMappingEnabled;
  42100. },
  42101. /**
  42102. * Sets wether tonemapping is enabled or not
  42103. */
  42104. set: function (value) {
  42105. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42106. },
  42107. enumerable: true,
  42108. configurable: true
  42109. });
  42110. ;
  42111. ;
  42112. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42113. /**
  42114. * The camera exposure used on this material.
  42115. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42116. * This corresponds to a photographic exposure.
  42117. */
  42118. get: function () {
  42119. return this._imageProcessingConfiguration.exposure;
  42120. },
  42121. /**
  42122. * The camera exposure used on this material.
  42123. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42124. * This corresponds to a photographic exposure.
  42125. */
  42126. set: function (value) {
  42127. this._imageProcessingConfiguration.exposure = value;
  42128. },
  42129. enumerable: true,
  42130. configurable: true
  42131. });
  42132. ;
  42133. ;
  42134. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42135. /**
  42136. * Gets The camera contrast used on this material.
  42137. */
  42138. get: function () {
  42139. return this._imageProcessingConfiguration.contrast;
  42140. },
  42141. /**
  42142. * Sets The camera contrast used on this material.
  42143. */
  42144. set: function (value) {
  42145. this._imageProcessingConfiguration.contrast = value;
  42146. },
  42147. enumerable: true,
  42148. configurable: true
  42149. });
  42150. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42151. /**
  42152. * Gets the Color Grading 2D Lookup Texture.
  42153. */
  42154. get: function () {
  42155. return this._imageProcessingConfiguration.colorGradingTexture;
  42156. },
  42157. /**
  42158. * Sets the Color Grading 2D Lookup Texture.
  42159. */
  42160. set: function (value) {
  42161. this._imageProcessingConfiguration.colorGradingTexture = value;
  42162. },
  42163. enumerable: true,
  42164. configurable: true
  42165. });
  42166. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42167. /**
  42168. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42169. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42170. * 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;
  42171. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42172. */
  42173. get: function () {
  42174. return this._imageProcessingConfiguration.colorCurves;
  42175. },
  42176. /**
  42177. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42178. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42179. * 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;
  42180. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42181. */
  42182. set: function (value) {
  42183. this._imageProcessingConfiguration.colorCurves = value;
  42184. },
  42185. enumerable: true,
  42186. configurable: true
  42187. });
  42188. /**
  42189. * Returns the name of this material class.
  42190. */
  42191. PBRMaterial.prototype.getClassName = function () {
  42192. return "PBRMaterial";
  42193. };
  42194. /**
  42195. * Returns an array of the actively used textures.
  42196. * @returns - Array of BaseTextures
  42197. */
  42198. PBRMaterial.prototype.getActiveTextures = function () {
  42199. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42200. if (this._albedoTexture) {
  42201. activeTextures.push(this._albedoTexture);
  42202. }
  42203. if (this._ambientTexture) {
  42204. activeTextures.push(this._ambientTexture);
  42205. }
  42206. if (this._opacityTexture) {
  42207. activeTextures.push(this._opacityTexture);
  42208. }
  42209. if (this._reflectionTexture) {
  42210. activeTextures.push(this._reflectionTexture);
  42211. }
  42212. if (this._emissiveTexture) {
  42213. activeTextures.push(this._emissiveTexture);
  42214. }
  42215. if (this._reflectivityTexture) {
  42216. activeTextures.push(this._reflectivityTexture);
  42217. }
  42218. if (this._metallicTexture) {
  42219. activeTextures.push(this._metallicTexture);
  42220. }
  42221. if (this._microSurfaceTexture) {
  42222. activeTextures.push(this._microSurfaceTexture);
  42223. }
  42224. if (this._bumpTexture) {
  42225. activeTextures.push(this._bumpTexture);
  42226. }
  42227. if (this._lightmapTexture) {
  42228. activeTextures.push(this._lightmapTexture);
  42229. }
  42230. if (this._refractionTexture) {
  42231. activeTextures.push(this._refractionTexture);
  42232. }
  42233. return activeTextures;
  42234. };
  42235. /**
  42236. * Checks to see if a texture is used in the material.
  42237. * @param texture - Base texture to use.
  42238. * @returns - Boolean specifying if a texture is used in the material.
  42239. */
  42240. PBRMaterial.prototype.hasTexture = function (texture) {
  42241. if (_super.prototype.hasTexture.call(this, texture)) {
  42242. return true;
  42243. }
  42244. if (this._albedoTexture === texture) {
  42245. return true;
  42246. }
  42247. if (this._ambientTexture === texture) {
  42248. return true;
  42249. }
  42250. if (this._opacityTexture === texture) {
  42251. return true;
  42252. }
  42253. if (this._reflectionTexture === texture) {
  42254. return true;
  42255. }
  42256. if (this._reflectivityTexture === texture) {
  42257. return true;
  42258. }
  42259. if (this._metallicTexture === texture) {
  42260. return true;
  42261. }
  42262. if (this._microSurfaceTexture === texture) {
  42263. return true;
  42264. }
  42265. if (this._bumpTexture === texture) {
  42266. return true;
  42267. }
  42268. if (this._lightmapTexture === texture) {
  42269. return true;
  42270. }
  42271. if (this._refractionTexture === texture) {
  42272. return true;
  42273. }
  42274. return false;
  42275. };
  42276. /**
  42277. * Makes a duplicate of the current material.
  42278. * @param name - name to use for the new material.
  42279. */
  42280. PBRMaterial.prototype.clone = function (name) {
  42281. var _this = this;
  42282. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  42283. clone.id = name;
  42284. clone.name = name;
  42285. return clone;
  42286. };
  42287. /**
  42288. * Serializes this PBR Material.
  42289. * @returns - An object with the serialized material.
  42290. */
  42291. PBRMaterial.prototype.serialize = function () {
  42292. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42293. serializationObject.customType = "BABYLON.PBRMaterial";
  42294. return serializationObject;
  42295. };
  42296. // Statics
  42297. /**
  42298. * Parses a PBR Material from a serialized object.
  42299. * @param source - Serialized object.
  42300. * @param scene - BJS scene instance.
  42301. * @param rootUrl - url for the scene object
  42302. * @returns - PBRMaterial
  42303. */
  42304. PBRMaterial.Parse = function (source, scene, rootUrl) {
  42305. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  42306. };
  42307. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  42308. /**
  42309. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42310. */
  42311. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  42312. /**
  42313. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42314. */
  42315. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  42316. /**
  42317. * 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.
  42318. * They are also discarded below the alpha cutoff threshold to improve performances.
  42319. */
  42320. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  42321. __decorate([
  42322. BABYLON.serialize(),
  42323. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42324. ], PBRMaterial.prototype, "directIntensity", void 0);
  42325. __decorate([
  42326. BABYLON.serialize(),
  42327. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42328. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  42329. __decorate([
  42330. BABYLON.serialize(),
  42331. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42332. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  42333. __decorate([
  42334. BABYLON.serialize(),
  42335. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42336. ], PBRMaterial.prototype, "specularIntensity", void 0);
  42337. __decorate([
  42338. BABYLON.serialize(),
  42339. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42340. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  42341. __decorate([
  42342. BABYLON.serializeAsTexture(),
  42343. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42344. ], PBRMaterial.prototype, "albedoTexture", void 0);
  42345. __decorate([
  42346. BABYLON.serializeAsTexture(),
  42347. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42348. ], PBRMaterial.prototype, "ambientTexture", void 0);
  42349. __decorate([
  42350. BABYLON.serialize(),
  42351. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42352. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  42353. __decorate([
  42354. BABYLON.serializeAsTexture(),
  42355. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42356. ], PBRMaterial.prototype, "opacityTexture", void 0);
  42357. __decorate([
  42358. BABYLON.serializeAsTexture(),
  42359. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42360. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  42361. __decorate([
  42362. BABYLON.serializeAsTexture(),
  42363. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42364. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  42365. __decorate([
  42366. BABYLON.serializeAsTexture(),
  42367. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42368. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  42369. __decorate([
  42370. BABYLON.serializeAsTexture(),
  42371. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42372. ], PBRMaterial.prototype, "metallicTexture", void 0);
  42373. __decorate([
  42374. BABYLON.serialize(),
  42375. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42376. ], PBRMaterial.prototype, "metallic", void 0);
  42377. __decorate([
  42378. BABYLON.serialize(),
  42379. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42380. ], PBRMaterial.prototype, "roughness", void 0);
  42381. __decorate([
  42382. BABYLON.serializeAsTexture(),
  42383. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42384. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  42385. __decorate([
  42386. BABYLON.serializeAsTexture(),
  42387. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42388. ], PBRMaterial.prototype, "bumpTexture", void 0);
  42389. __decorate([
  42390. BABYLON.serializeAsTexture(),
  42391. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42392. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  42393. __decorate([
  42394. BABYLON.serializeAsTexture(),
  42395. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42396. ], PBRMaterial.prototype, "refractionTexture", void 0);
  42397. __decorate([
  42398. BABYLON.serializeAsColor3("ambient"),
  42399. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42400. ], PBRMaterial.prototype, "ambientColor", void 0);
  42401. __decorate([
  42402. BABYLON.serializeAsColor3("albedo"),
  42403. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42404. ], PBRMaterial.prototype, "albedoColor", void 0);
  42405. __decorate([
  42406. BABYLON.serializeAsColor3("reflectivity"),
  42407. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42408. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  42409. __decorate([
  42410. BABYLON.serializeAsColor3("reflection"),
  42411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42412. ], PBRMaterial.prototype, "reflectionColor", void 0);
  42413. __decorate([
  42414. BABYLON.serializeAsColor3("emissive"),
  42415. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42416. ], PBRMaterial.prototype, "emissiveColor", void 0);
  42417. __decorate([
  42418. BABYLON.serialize(),
  42419. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42420. ], PBRMaterial.prototype, "microSurface", void 0);
  42421. __decorate([
  42422. BABYLON.serialize(),
  42423. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42424. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  42425. __decorate([
  42426. BABYLON.serialize(),
  42427. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42428. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  42429. __decorate([
  42430. BABYLON.serialize(),
  42431. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42432. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  42433. __decorate([
  42434. BABYLON.serialize(),
  42435. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42436. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42437. __decorate([
  42438. BABYLON.serialize(),
  42439. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42440. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  42441. __decorate([
  42442. BABYLON.serialize(),
  42443. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42444. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  42445. __decorate([
  42446. BABYLON.serialize(),
  42447. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42448. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  42449. __decorate([
  42450. BABYLON.serialize(),
  42451. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42452. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  42453. __decorate([
  42454. BABYLON.serialize(),
  42455. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42456. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  42457. __decorate([
  42458. BABYLON.serialize(),
  42459. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42460. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  42461. __decorate([
  42462. BABYLON.serialize(),
  42463. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42464. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  42465. __decorate([
  42466. BABYLON.serialize(),
  42467. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42468. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  42469. __decorate([
  42470. BABYLON.serialize(),
  42471. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42472. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  42473. __decorate([
  42474. BABYLON.serialize(),
  42475. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42476. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  42477. __decorate([
  42478. BABYLON.serialize(),
  42479. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42480. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  42481. __decorate([
  42482. BABYLON.serialize(),
  42483. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42484. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  42485. __decorate([
  42486. BABYLON.serialize(),
  42487. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42488. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  42489. __decorate([
  42490. BABYLON.serialize(),
  42491. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42492. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42493. __decorate([
  42494. BABYLON.serialize(),
  42495. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42496. ], PBRMaterial.prototype, "useParallax", void 0);
  42497. __decorate([
  42498. BABYLON.serialize(),
  42499. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42500. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  42501. __decorate([
  42502. BABYLON.serialize(),
  42503. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42504. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  42505. __decorate([
  42506. BABYLON.serialize(),
  42507. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42508. ], PBRMaterial.prototype, "disableLighting", void 0);
  42509. __decorate([
  42510. BABYLON.serialize(),
  42511. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42512. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  42513. __decorate([
  42514. BABYLON.serialize(),
  42515. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42516. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  42517. __decorate([
  42518. BABYLON.serialize(),
  42519. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42520. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  42521. __decorate([
  42522. BABYLON.serialize(),
  42523. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42524. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  42525. __decorate([
  42526. BABYLON.serialize(),
  42527. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42528. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  42529. __decorate([
  42530. BABYLON.serialize(),
  42531. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42532. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  42533. __decorate([
  42534. BABYLON.serialize(),
  42535. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42536. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  42537. __decorate([
  42538. BABYLON.serializeAsTexture(),
  42539. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42540. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  42541. __decorate([
  42542. BABYLON.serialize(),
  42543. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42544. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  42545. __decorate([
  42546. BABYLON.serialize(),
  42547. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42548. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  42549. __decorate([
  42550. BABYLON.serialize(),
  42551. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42552. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  42553. return PBRMaterial;
  42554. }(BABYLON.PBRBaseMaterial));
  42555. BABYLON.PBRMaterial = PBRMaterial;
  42556. })(BABYLON || (BABYLON = {}));
  42557. //# sourceMappingURL=babylon.pbrMaterial.js.map
  42558. var BABYLON;
  42559. (function (BABYLON) {
  42560. /**
  42561. * The PBR material of BJS following the metal roughness convention.
  42562. *
  42563. * This fits to the PBR convention in the GLTF definition:
  42564. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  42565. */
  42566. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  42567. __extends(PBRMetallicRoughnessMaterial, _super);
  42568. /**
  42569. * Instantiates a new PBRMetalRoughnessMaterial instance.
  42570. *
  42571. * @param name The material name
  42572. * @param scene The scene the material will be use in.
  42573. */
  42574. function PBRMetallicRoughnessMaterial(name, scene) {
  42575. var _this = _super.call(this, name, scene) || this;
  42576. _this._useRoughnessFromMetallicTextureAlpha = false;
  42577. _this._useRoughnessFromMetallicTextureGreen = true;
  42578. _this._useMetallnessFromMetallicTextureBlue = true;
  42579. _this._forceMetallicWorkflow = true;
  42580. return _this;
  42581. }
  42582. /**
  42583. * Return the currrent class name of the material.
  42584. */
  42585. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  42586. return "PBRMetallicRoughnessMaterial";
  42587. };
  42588. /**
  42589. * Return the active textures of the material.
  42590. */
  42591. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  42592. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42593. if (this.baseTexture) {
  42594. activeTextures.push(this.baseTexture);
  42595. }
  42596. if (this.metallicRoughnessTexture) {
  42597. activeTextures.push(this.metallicRoughnessTexture);
  42598. }
  42599. return activeTextures;
  42600. };
  42601. /**
  42602. * Checks to see if a texture is used in the material.
  42603. * @param texture - Base texture to use.
  42604. * @returns - Boolean specifying if a texture is used in the material.
  42605. */
  42606. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  42607. if (_super.prototype.hasTexture.call(this, texture)) {
  42608. return true;
  42609. }
  42610. if (this.baseTexture === texture) {
  42611. return true;
  42612. }
  42613. if (this.metallicRoughnessTexture === texture) {
  42614. return true;
  42615. }
  42616. return false;
  42617. };
  42618. /**
  42619. * Makes a duplicate of the current material.
  42620. * @param name - name to use for the new material.
  42621. */
  42622. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  42623. var _this = this;
  42624. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  42625. clone.id = name;
  42626. clone.name = name;
  42627. return clone;
  42628. };
  42629. /**
  42630. * Serialize the material to a parsable JSON object.
  42631. */
  42632. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  42633. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42634. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  42635. return serializationObject;
  42636. };
  42637. /**
  42638. * Parses a JSON object correponding to the serialize function.
  42639. */
  42640. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  42641. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  42642. };
  42643. __decorate([
  42644. BABYLON.serializeAsColor3(),
  42645. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42646. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  42647. __decorate([
  42648. BABYLON.serializeAsTexture(),
  42649. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42650. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  42651. __decorate([
  42652. BABYLON.serialize(),
  42653. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42654. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  42655. __decorate([
  42656. BABYLON.serialize(),
  42657. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42658. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  42659. __decorate([
  42660. BABYLON.serializeAsTexture(),
  42661. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  42662. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  42663. return PBRMetallicRoughnessMaterial;
  42664. }(BABYLON.PBRBaseSimpleMaterial));
  42665. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  42666. })(BABYLON || (BABYLON = {}));
  42667. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  42668. var BABYLON;
  42669. (function (BABYLON) {
  42670. /**
  42671. * The PBR material of BJS following the specular glossiness convention.
  42672. *
  42673. * This fits to the PBR convention in the GLTF definition:
  42674. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  42675. */
  42676. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  42677. __extends(PBRSpecularGlossinessMaterial, _super);
  42678. /**
  42679. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  42680. *
  42681. * @param name The material name
  42682. * @param scene The scene the material will be use in.
  42683. */
  42684. function PBRSpecularGlossinessMaterial(name, scene) {
  42685. var _this = _super.call(this, name, scene) || this;
  42686. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  42687. return _this;
  42688. }
  42689. /**
  42690. * Return the currrent class name of the material.
  42691. */
  42692. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  42693. return "PBRSpecularGlossinessMaterial";
  42694. };
  42695. /**
  42696. * Return the active textures of the material.
  42697. */
  42698. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  42699. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42700. if (this.diffuseTexture) {
  42701. activeTextures.push(this.diffuseTexture);
  42702. }
  42703. if (this.specularGlossinessTexture) {
  42704. activeTextures.push(this.specularGlossinessTexture);
  42705. }
  42706. return activeTextures;
  42707. };
  42708. /**
  42709. * Checks to see if a texture is used in the material.
  42710. * @param texture - Base texture to use.
  42711. * @returns - Boolean specifying if a texture is used in the material.
  42712. */
  42713. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  42714. if (_super.prototype.hasTexture.call(this, texture)) {
  42715. return true;
  42716. }
  42717. if (this.diffuseTexture === texture) {
  42718. return true;
  42719. }
  42720. if (this.specularGlossinessTexture === texture) {
  42721. return true;
  42722. }
  42723. return false;
  42724. };
  42725. /**
  42726. * Makes a duplicate of the current material.
  42727. * @param name - name to use for the new material.
  42728. */
  42729. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  42730. var _this = this;
  42731. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  42732. clone.id = name;
  42733. clone.name = name;
  42734. return clone;
  42735. };
  42736. /**
  42737. * Serialize the material to a parsable JSON object.
  42738. */
  42739. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  42740. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42741. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  42742. return serializationObject;
  42743. };
  42744. /**
  42745. * Parses a JSON object correponding to the serialize function.
  42746. */
  42747. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  42748. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  42749. };
  42750. __decorate([
  42751. BABYLON.serializeAsColor3("diffuse"),
  42752. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42753. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  42754. __decorate([
  42755. BABYLON.serializeAsTexture(),
  42756. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42757. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  42758. __decorate([
  42759. BABYLON.serializeAsColor3("specular"),
  42760. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  42761. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  42762. __decorate([
  42763. BABYLON.serialize(),
  42764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  42765. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  42766. __decorate([
  42767. BABYLON.serializeAsTexture(),
  42768. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  42769. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  42770. return PBRSpecularGlossinessMaterial;
  42771. }(BABYLON.PBRBaseSimpleMaterial));
  42772. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  42773. })(BABYLON || (BABYLON = {}));
  42774. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  42775. var BABYLON;
  42776. (function (BABYLON) {
  42777. BABYLON.CameraInputTypes = {};
  42778. var CameraInputsManager = /** @class */ (function () {
  42779. function CameraInputsManager(camera) {
  42780. this.attached = {};
  42781. this.camera = camera;
  42782. this.checkInputs = function () { };
  42783. }
  42784. /**
  42785. * Add an input method to a camera.
  42786. * builtin inputs example: camera.inputs.addGamepad();
  42787. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  42788. * @param input camera input method
  42789. */
  42790. CameraInputsManager.prototype.add = function (input) {
  42791. var type = input.getSimpleName();
  42792. if (this.attached[type]) {
  42793. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  42794. return;
  42795. }
  42796. this.attached[type] = input;
  42797. input.camera = this.camera;
  42798. //for checkInputs, we are dynamically creating a function
  42799. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  42800. if (input.checkInputs) {
  42801. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42802. }
  42803. if (this.attachedElement) {
  42804. input.attachControl(this.attachedElement);
  42805. }
  42806. };
  42807. /**
  42808. * Remove a specific input method from a camera
  42809. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  42810. * @param inputToRemove camera input method
  42811. */
  42812. CameraInputsManager.prototype.remove = function (inputToRemove) {
  42813. for (var cam in this.attached) {
  42814. var input = this.attached[cam];
  42815. if (input === inputToRemove) {
  42816. input.detachControl(this.attachedElement);
  42817. input.camera = null;
  42818. delete this.attached[cam];
  42819. this.rebuildInputCheck();
  42820. }
  42821. }
  42822. };
  42823. CameraInputsManager.prototype.removeByType = function (inputType) {
  42824. for (var cam in this.attached) {
  42825. var input = this.attached[cam];
  42826. if (input.getClassName() === inputType) {
  42827. input.detachControl(this.attachedElement);
  42828. input.camera = null;
  42829. delete this.attached[cam];
  42830. this.rebuildInputCheck();
  42831. }
  42832. }
  42833. };
  42834. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  42835. var current = this.checkInputs;
  42836. return function () {
  42837. current();
  42838. fn();
  42839. };
  42840. };
  42841. CameraInputsManager.prototype.attachInput = function (input) {
  42842. if (this.attachedElement) {
  42843. input.attachControl(this.attachedElement, this.noPreventDefault);
  42844. }
  42845. };
  42846. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  42847. if (noPreventDefault === void 0) { noPreventDefault = false; }
  42848. if (this.attachedElement) {
  42849. return;
  42850. }
  42851. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  42852. this.attachedElement = element;
  42853. this.noPreventDefault = noPreventDefault;
  42854. for (var cam in this.attached) {
  42855. this.attached[cam].attachControl(element, noPreventDefault);
  42856. }
  42857. };
  42858. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  42859. if (disconnect === void 0) { disconnect = false; }
  42860. if (this.attachedElement !== element) {
  42861. return;
  42862. }
  42863. for (var cam in this.attached) {
  42864. this.attached[cam].detachControl(element);
  42865. if (disconnect) {
  42866. this.attached[cam].camera = null;
  42867. }
  42868. }
  42869. this.attachedElement = null;
  42870. };
  42871. CameraInputsManager.prototype.rebuildInputCheck = function () {
  42872. this.checkInputs = function () { };
  42873. for (var cam in this.attached) {
  42874. var input = this.attached[cam];
  42875. if (input.checkInputs) {
  42876. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42877. }
  42878. }
  42879. };
  42880. /**
  42881. * Remove all attached input methods from a camera
  42882. */
  42883. CameraInputsManager.prototype.clear = function () {
  42884. if (this.attachedElement) {
  42885. this.detachElement(this.attachedElement, true);
  42886. }
  42887. this.attached = {};
  42888. this.attachedElement = null;
  42889. this.checkInputs = function () { };
  42890. };
  42891. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  42892. var inputs = {};
  42893. for (var cam in this.attached) {
  42894. var input = this.attached[cam];
  42895. var res = BABYLON.SerializationHelper.Serialize(input);
  42896. inputs[input.getClassName()] = res;
  42897. }
  42898. serializedCamera.inputsmgr = inputs;
  42899. };
  42900. CameraInputsManager.prototype.parse = function (parsedCamera) {
  42901. var parsedInputs = parsedCamera.inputsmgr;
  42902. if (parsedInputs) {
  42903. this.clear();
  42904. for (var n in parsedInputs) {
  42905. var construct = BABYLON.CameraInputTypes[n];
  42906. if (construct) {
  42907. var parsedinput = parsedInputs[n];
  42908. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  42909. this.add(input);
  42910. }
  42911. }
  42912. }
  42913. else {
  42914. //2016-03-08 this part is for managing backward compatibility
  42915. for (var n in this.attached) {
  42916. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  42917. if (construct) {
  42918. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  42919. this.remove(this.attached[n]);
  42920. this.add(input);
  42921. }
  42922. }
  42923. }
  42924. };
  42925. return CameraInputsManager;
  42926. }());
  42927. BABYLON.CameraInputsManager = CameraInputsManager;
  42928. })(BABYLON || (BABYLON = {}));
  42929. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  42930. var BABYLON;
  42931. (function (BABYLON) {
  42932. var TargetCamera = /** @class */ (function (_super) {
  42933. __extends(TargetCamera, _super);
  42934. function TargetCamera(name, position, scene) {
  42935. var _this = _super.call(this, name, position, scene) || this;
  42936. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  42937. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  42938. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  42939. _this.speed = 2.0;
  42940. _this.noRotationConstraint = false;
  42941. _this.lockedTarget = null;
  42942. _this._currentTarget = BABYLON.Vector3.Zero();
  42943. _this._viewMatrix = BABYLON.Matrix.Zero();
  42944. _this._camMatrix = BABYLON.Matrix.Zero();
  42945. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  42946. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  42947. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  42948. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  42949. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  42950. _this._lookAtTemp = BABYLON.Matrix.Zero();
  42951. _this._tempMatrix = BABYLON.Matrix.Zero();
  42952. return _this;
  42953. }
  42954. TargetCamera.prototype.getFrontPosition = function (distance) {
  42955. this.getWorldMatrix();
  42956. var direction = this.getTarget().subtract(this.position);
  42957. direction.normalize();
  42958. direction.scaleInPlace(distance);
  42959. return this.globalPosition.add(direction);
  42960. };
  42961. TargetCamera.prototype._getLockedTargetPosition = function () {
  42962. if (!this.lockedTarget) {
  42963. return null;
  42964. }
  42965. if (this.lockedTarget.absolutePosition) {
  42966. this.lockedTarget.computeWorldMatrix();
  42967. }
  42968. return this.lockedTarget.absolutePosition || this.lockedTarget;
  42969. };
  42970. TargetCamera.prototype.storeState = function () {
  42971. this._storedPosition = this.position.clone();
  42972. this._storedRotation = this.rotation.clone();
  42973. if (this.rotationQuaternion) {
  42974. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  42975. }
  42976. return _super.prototype.storeState.call(this);
  42977. };
  42978. /**
  42979. * Restored camera state. You must call storeState() first
  42980. */
  42981. TargetCamera.prototype._restoreStateValues = function () {
  42982. if (!_super.prototype._restoreStateValues.call(this)) {
  42983. return false;
  42984. }
  42985. this.position = this._storedPosition.clone();
  42986. this.rotation = this._storedRotation.clone();
  42987. if (this.rotationQuaternion) {
  42988. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  42989. }
  42990. this.cameraDirection.copyFromFloats(0, 0, 0);
  42991. this.cameraRotation.copyFromFloats(0, 0);
  42992. return true;
  42993. };
  42994. // Cache
  42995. TargetCamera.prototype._initCache = function () {
  42996. _super.prototype._initCache.call(this);
  42997. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42998. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42999. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43000. };
  43001. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  43002. if (!ignoreParentClass) {
  43003. _super.prototype._updateCache.call(this);
  43004. }
  43005. var lockedTargetPosition = this._getLockedTargetPosition();
  43006. if (!lockedTargetPosition) {
  43007. this._cache.lockedTarget = null;
  43008. }
  43009. else {
  43010. if (!this._cache.lockedTarget) {
  43011. this._cache.lockedTarget = lockedTargetPosition.clone();
  43012. }
  43013. else {
  43014. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  43015. }
  43016. }
  43017. this._cache.rotation.copyFrom(this.rotation);
  43018. if (this.rotationQuaternion)
  43019. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43020. };
  43021. // Synchronized
  43022. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  43023. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  43024. return false;
  43025. }
  43026. var lockedTargetPosition = this._getLockedTargetPosition();
  43027. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  43028. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  43029. };
  43030. // Methods
  43031. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  43032. var engine = this.getEngine();
  43033. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  43034. };
  43035. // Target
  43036. TargetCamera.prototype.setTarget = function (target) {
  43037. this.upVector.normalize();
  43038. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  43039. this._camMatrix.invert();
  43040. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  43041. var vDir = target.subtract(this.position);
  43042. if (vDir.x >= 0.0) {
  43043. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  43044. }
  43045. else {
  43046. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  43047. }
  43048. this.rotation.z = 0;
  43049. if (isNaN(this.rotation.x)) {
  43050. this.rotation.x = 0;
  43051. }
  43052. if (isNaN(this.rotation.y)) {
  43053. this.rotation.y = 0;
  43054. }
  43055. if (isNaN(this.rotation.z)) {
  43056. this.rotation.z = 0;
  43057. }
  43058. if (this.rotationQuaternion) {
  43059. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43060. }
  43061. };
  43062. /**
  43063. * Return the current target position of the camera. This value is expressed in local space.
  43064. */
  43065. TargetCamera.prototype.getTarget = function () {
  43066. return this._currentTarget;
  43067. };
  43068. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43069. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43070. };
  43071. TargetCamera.prototype._updatePosition = function () {
  43072. if (this.parent) {
  43073. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43074. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43075. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43076. return;
  43077. }
  43078. this.position.addInPlace(this.cameraDirection);
  43079. };
  43080. TargetCamera.prototype._checkInputs = function () {
  43081. var needToMove = this._decideIfNeedsToMove();
  43082. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43083. // Move
  43084. if (needToMove) {
  43085. this._updatePosition();
  43086. }
  43087. // Rotate
  43088. if (needToRotate) {
  43089. this.rotation.x += this.cameraRotation.x;
  43090. this.rotation.y += this.cameraRotation.y;
  43091. //rotate, if quaternion is set and rotation was used
  43092. if (this.rotationQuaternion) {
  43093. var len = this.rotation.lengthSquared();
  43094. if (len) {
  43095. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43096. }
  43097. }
  43098. if (!this.noRotationConstraint) {
  43099. var limit = (Math.PI / 2) * 0.95;
  43100. if (this.rotation.x > limit)
  43101. this.rotation.x = limit;
  43102. if (this.rotation.x < -limit)
  43103. this.rotation.x = -limit;
  43104. }
  43105. }
  43106. // Inertia
  43107. if (needToMove) {
  43108. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43109. this.cameraDirection.x = 0;
  43110. }
  43111. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43112. this.cameraDirection.y = 0;
  43113. }
  43114. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43115. this.cameraDirection.z = 0;
  43116. }
  43117. this.cameraDirection.scaleInPlace(this.inertia);
  43118. }
  43119. if (needToRotate) {
  43120. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43121. this.cameraRotation.x = 0;
  43122. }
  43123. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43124. this.cameraRotation.y = 0;
  43125. }
  43126. this.cameraRotation.scaleInPlace(this.inertia);
  43127. }
  43128. _super.prototype._checkInputs.call(this);
  43129. };
  43130. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43131. if (this.rotationQuaternion) {
  43132. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43133. }
  43134. else {
  43135. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43136. }
  43137. //update the up vector!
  43138. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43139. };
  43140. TargetCamera.prototype._getViewMatrix = function () {
  43141. if (this.lockedTarget) {
  43142. this.setTarget(this._getLockedTargetPosition());
  43143. }
  43144. // Compute
  43145. this._updateCameraRotationMatrix();
  43146. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43147. // Computing target and final matrix
  43148. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43149. if (this.getScene().useRightHandedSystem) {
  43150. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43151. }
  43152. else {
  43153. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43154. }
  43155. return this._viewMatrix;
  43156. };
  43157. /**
  43158. * @override
  43159. * Override Camera.createRigCamera
  43160. */
  43161. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43162. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43163. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43164. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43165. if (!this.rotationQuaternion) {
  43166. this.rotationQuaternion = new BABYLON.Quaternion();
  43167. }
  43168. rigCamera._cameraRigParams = {};
  43169. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43170. }
  43171. return rigCamera;
  43172. }
  43173. return null;
  43174. };
  43175. /**
  43176. * @override
  43177. * Override Camera._updateRigCameras
  43178. */
  43179. TargetCamera.prototype._updateRigCameras = function () {
  43180. var camLeft = this._rigCameras[0];
  43181. var camRight = this._rigCameras[1];
  43182. switch (this.cameraRigMode) {
  43183. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43184. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43185. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43186. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43187. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43188. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43189. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43190. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43191. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43192. camLeft.setTarget(this.getTarget());
  43193. camRight.setTarget(this.getTarget());
  43194. break;
  43195. case BABYLON.Camera.RIG_MODE_VR:
  43196. if (camLeft.rotationQuaternion) {
  43197. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43198. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43199. }
  43200. else {
  43201. camLeft.rotation.copyFrom(this.rotation);
  43202. camRight.rotation.copyFrom(this.rotation);
  43203. }
  43204. camLeft.position.copyFrom(this.position);
  43205. camRight.position.copyFrom(this.position);
  43206. break;
  43207. }
  43208. _super.prototype._updateRigCameras.call(this);
  43209. };
  43210. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43211. if (!this._rigCamTransformMatrix) {
  43212. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43213. }
  43214. var target = this.getTarget();
  43215. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43216. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43217. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43218. };
  43219. TargetCamera.prototype.getClassName = function () {
  43220. return "TargetCamera";
  43221. };
  43222. __decorate([
  43223. BABYLON.serializeAsVector3()
  43224. ], TargetCamera.prototype, "rotation", void 0);
  43225. __decorate([
  43226. BABYLON.serialize()
  43227. ], TargetCamera.prototype, "speed", void 0);
  43228. __decorate([
  43229. BABYLON.serializeAsMeshReference("lockedTargetId")
  43230. ], TargetCamera.prototype, "lockedTarget", void 0);
  43231. return TargetCamera;
  43232. }(BABYLON.Camera));
  43233. BABYLON.TargetCamera = TargetCamera;
  43234. })(BABYLON || (BABYLON = {}));
  43235. //# sourceMappingURL=babylon.targetCamera.js.map
  43236. var BABYLON;
  43237. (function (BABYLON) {
  43238. var FreeCameraMouseInput = /** @class */ (function () {
  43239. function FreeCameraMouseInput(touchEnabled) {
  43240. if (touchEnabled === void 0) { touchEnabled = true; }
  43241. this.touchEnabled = touchEnabled;
  43242. this.buttons = [0, 1, 2];
  43243. this.angularSensibility = 2000.0;
  43244. this.previousPosition = null;
  43245. }
  43246. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43247. var _this = this;
  43248. var engine = this.camera.getEngine();
  43249. if (!this._pointerInput) {
  43250. this._pointerInput = function (p, s) {
  43251. var evt = p.event;
  43252. if (engine.isInVRExclusivePointerMode) {
  43253. return;
  43254. }
  43255. if (!_this.touchEnabled && evt.pointerType === "touch") {
  43256. return;
  43257. }
  43258. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43259. return;
  43260. }
  43261. var srcElement = (evt.srcElement || evt.target);
  43262. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43263. try {
  43264. srcElement.setPointerCapture(evt.pointerId);
  43265. }
  43266. catch (e) {
  43267. //Nothing to do with the error. Execution will continue.
  43268. }
  43269. _this.previousPosition = {
  43270. x: evt.clientX,
  43271. y: evt.clientY
  43272. };
  43273. if (!noPreventDefault) {
  43274. evt.preventDefault();
  43275. element.focus();
  43276. }
  43277. }
  43278. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43279. try {
  43280. srcElement.releasePointerCapture(evt.pointerId);
  43281. }
  43282. catch (e) {
  43283. //Nothing to do with the error.
  43284. }
  43285. _this.previousPosition = null;
  43286. if (!noPreventDefault) {
  43287. evt.preventDefault();
  43288. }
  43289. }
  43290. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43291. if (!_this.previousPosition || engine.isPointerLock) {
  43292. return;
  43293. }
  43294. var offsetX = evt.clientX - _this.previousPosition.x;
  43295. var offsetY = evt.clientY - _this.previousPosition.y;
  43296. if (_this.camera.getScene().useRightHandedSystem) {
  43297. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43298. }
  43299. else {
  43300. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43301. }
  43302. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43303. _this.previousPosition = {
  43304. x: evt.clientX,
  43305. y: evt.clientY
  43306. };
  43307. if (!noPreventDefault) {
  43308. evt.preventDefault();
  43309. }
  43310. }
  43311. };
  43312. }
  43313. this._onMouseMove = function (evt) {
  43314. if (!engine.isPointerLock) {
  43315. return;
  43316. }
  43317. if (engine.isInVRExclusivePointerMode) {
  43318. return;
  43319. }
  43320. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43321. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43322. if (_this.camera.getScene().useRightHandedSystem) {
  43323. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43324. }
  43325. else {
  43326. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43327. }
  43328. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43329. _this.previousPosition = null;
  43330. if (!noPreventDefault) {
  43331. evt.preventDefault();
  43332. }
  43333. };
  43334. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  43335. element.addEventListener("mousemove", this._onMouseMove, false);
  43336. };
  43337. FreeCameraMouseInput.prototype.detachControl = function (element) {
  43338. if (this._observer && element) {
  43339. this.camera.getScene().onPointerObservable.remove(this._observer);
  43340. if (this._onMouseMove) {
  43341. element.removeEventListener("mousemove", this._onMouseMove);
  43342. }
  43343. this._observer = null;
  43344. this._onMouseMove = null;
  43345. this.previousPosition = null;
  43346. }
  43347. };
  43348. FreeCameraMouseInput.prototype.getClassName = function () {
  43349. return "FreeCameraMouseInput";
  43350. };
  43351. FreeCameraMouseInput.prototype.getSimpleName = function () {
  43352. return "mouse";
  43353. };
  43354. __decorate([
  43355. BABYLON.serialize()
  43356. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  43357. __decorate([
  43358. BABYLON.serialize()
  43359. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  43360. return FreeCameraMouseInput;
  43361. }());
  43362. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  43363. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  43364. })(BABYLON || (BABYLON = {}));
  43365. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  43366. var BABYLON;
  43367. (function (BABYLON) {
  43368. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  43369. function FreeCameraKeyboardMoveInput() {
  43370. this._keys = new Array();
  43371. this.keysUp = [38];
  43372. this.keysDown = [40];
  43373. this.keysLeft = [37];
  43374. this.keysRight = [39];
  43375. }
  43376. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43377. var _this = this;
  43378. if (this._onCanvasBlurObserver) {
  43379. return;
  43380. }
  43381. this._scene = this.camera.getScene();
  43382. this._engine = this._scene.getEngine();
  43383. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43384. _this._keys = [];
  43385. });
  43386. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43387. var evt = info.event;
  43388. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43389. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43390. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43391. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43392. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43393. var index = _this._keys.indexOf(evt.keyCode);
  43394. if (index === -1) {
  43395. _this._keys.push(evt.keyCode);
  43396. }
  43397. if (!noPreventDefault) {
  43398. evt.preventDefault();
  43399. }
  43400. }
  43401. }
  43402. else {
  43403. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43404. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43405. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43406. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43407. var index = _this._keys.indexOf(evt.keyCode);
  43408. if (index >= 0) {
  43409. _this._keys.splice(index, 1);
  43410. }
  43411. if (!noPreventDefault) {
  43412. evt.preventDefault();
  43413. }
  43414. }
  43415. }
  43416. });
  43417. };
  43418. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43419. if (this._scene) {
  43420. if (this._onKeyboardObserver) {
  43421. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43422. }
  43423. if (this._onCanvasBlurObserver) {
  43424. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43425. }
  43426. this._onKeyboardObserver = null;
  43427. this._onCanvasBlurObserver = null;
  43428. }
  43429. this._keys = [];
  43430. };
  43431. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43432. if (this._onKeyboardObserver) {
  43433. var camera = this.camera;
  43434. // Keyboard
  43435. for (var index = 0; index < this._keys.length; index++) {
  43436. var keyCode = this._keys[index];
  43437. var speed = camera._computeLocalCameraSpeed();
  43438. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43439. camera._localDirection.copyFromFloats(-speed, 0, 0);
  43440. }
  43441. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43442. camera._localDirection.copyFromFloats(0, 0, speed);
  43443. }
  43444. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43445. camera._localDirection.copyFromFloats(speed, 0, 0);
  43446. }
  43447. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43448. camera._localDirection.copyFromFloats(0, 0, -speed);
  43449. }
  43450. if (camera.getScene().useRightHandedSystem) {
  43451. camera._localDirection.z *= -1;
  43452. }
  43453. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  43454. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  43455. camera.cameraDirection.addInPlace(camera._transformedDirection);
  43456. }
  43457. }
  43458. };
  43459. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  43460. return "FreeCameraKeyboardMoveInput";
  43461. };
  43462. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  43463. this._keys = [];
  43464. };
  43465. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43466. return "keyboard";
  43467. };
  43468. __decorate([
  43469. BABYLON.serialize()
  43470. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43471. __decorate([
  43472. BABYLON.serialize()
  43473. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43474. __decorate([
  43475. BABYLON.serialize()
  43476. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43477. __decorate([
  43478. BABYLON.serialize()
  43479. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43480. return FreeCameraKeyboardMoveInput;
  43481. }());
  43482. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  43483. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  43484. })(BABYLON || (BABYLON = {}));
  43485. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  43486. var BABYLON;
  43487. (function (BABYLON) {
  43488. var FreeCameraInputsManager = /** @class */ (function (_super) {
  43489. __extends(FreeCameraInputsManager, _super);
  43490. function FreeCameraInputsManager(camera) {
  43491. return _super.call(this, camera) || this;
  43492. }
  43493. FreeCameraInputsManager.prototype.addKeyboard = function () {
  43494. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  43495. return this;
  43496. };
  43497. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  43498. if (touchEnabled === void 0) { touchEnabled = true; }
  43499. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  43500. return this;
  43501. };
  43502. FreeCameraInputsManager.prototype.addGamepad = function () {
  43503. this.add(new BABYLON.FreeCameraGamepadInput());
  43504. return this;
  43505. };
  43506. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  43507. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  43508. return this;
  43509. };
  43510. FreeCameraInputsManager.prototype.addTouch = function () {
  43511. this.add(new BABYLON.FreeCameraTouchInput());
  43512. return this;
  43513. };
  43514. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  43515. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  43516. return this;
  43517. };
  43518. return FreeCameraInputsManager;
  43519. }(BABYLON.CameraInputsManager));
  43520. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  43521. })(BABYLON || (BABYLON = {}));
  43522. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  43523. var BABYLON;
  43524. (function (BABYLON) {
  43525. var FreeCamera = /** @class */ (function (_super) {
  43526. __extends(FreeCamera, _super);
  43527. function FreeCamera(name, position, scene) {
  43528. var _this = _super.call(this, name, position, scene) || this;
  43529. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  43530. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  43531. _this.checkCollisions = false;
  43532. _this.applyGravity = false;
  43533. _this._needMoveForGravity = false;
  43534. _this._oldPosition = BABYLON.Vector3.Zero();
  43535. _this._diffPosition = BABYLON.Vector3.Zero();
  43536. _this._newPosition = BABYLON.Vector3.Zero();
  43537. // Collisions
  43538. _this._collisionMask = -1;
  43539. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43540. if (collidedMesh === void 0) { collidedMesh = null; }
  43541. //TODO move this to the collision coordinator!
  43542. if (_this.getScene().workerCollisions)
  43543. newPosition.multiplyInPlace(_this._collider._radius);
  43544. var updatePosition = function (newPos) {
  43545. _this._newPosition.copyFrom(newPos);
  43546. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  43547. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  43548. _this.position.addInPlace(_this._diffPosition);
  43549. if (_this.onCollide && collidedMesh) {
  43550. _this.onCollide(collidedMesh);
  43551. }
  43552. }
  43553. };
  43554. updatePosition(newPosition);
  43555. };
  43556. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  43557. _this.inputs.addKeyboard().addMouse();
  43558. return _this;
  43559. }
  43560. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  43561. //-- begin properties for backward compatibility for inputs
  43562. /**
  43563. * Gets the input sensibility for a mouse input. (default is 2000.0)
  43564. * Higher values reduce sensitivity.
  43565. */
  43566. get: function () {
  43567. var mouse = this.inputs.attached["mouse"];
  43568. if (mouse)
  43569. return mouse.angularSensibility;
  43570. return 0;
  43571. },
  43572. /**
  43573. * Sets the input sensibility for a mouse input. (default is 2000.0)
  43574. * Higher values reduce sensitivity.
  43575. */
  43576. set: function (value) {
  43577. var mouse = this.inputs.attached["mouse"];
  43578. if (mouse)
  43579. mouse.angularSensibility = value;
  43580. },
  43581. enumerable: true,
  43582. configurable: true
  43583. });
  43584. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  43585. get: function () {
  43586. var keyboard = this.inputs.attached["keyboard"];
  43587. if (keyboard)
  43588. return keyboard.keysUp;
  43589. return [];
  43590. },
  43591. set: function (value) {
  43592. var keyboard = this.inputs.attached["keyboard"];
  43593. if (keyboard)
  43594. keyboard.keysUp = value;
  43595. },
  43596. enumerable: true,
  43597. configurable: true
  43598. });
  43599. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  43600. get: function () {
  43601. var keyboard = this.inputs.attached["keyboard"];
  43602. if (keyboard)
  43603. return keyboard.keysDown;
  43604. return [];
  43605. },
  43606. set: function (value) {
  43607. var keyboard = this.inputs.attached["keyboard"];
  43608. if (keyboard)
  43609. keyboard.keysDown = value;
  43610. },
  43611. enumerable: true,
  43612. configurable: true
  43613. });
  43614. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  43615. get: function () {
  43616. var keyboard = this.inputs.attached["keyboard"];
  43617. if (keyboard)
  43618. return keyboard.keysLeft;
  43619. return [];
  43620. },
  43621. set: function (value) {
  43622. var keyboard = this.inputs.attached["keyboard"];
  43623. if (keyboard)
  43624. keyboard.keysLeft = value;
  43625. },
  43626. enumerable: true,
  43627. configurable: true
  43628. });
  43629. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  43630. get: function () {
  43631. var keyboard = this.inputs.attached["keyboard"];
  43632. if (keyboard)
  43633. return keyboard.keysRight;
  43634. return [];
  43635. },
  43636. set: function (value) {
  43637. var keyboard = this.inputs.attached["keyboard"];
  43638. if (keyboard)
  43639. keyboard.keysRight = value;
  43640. },
  43641. enumerable: true,
  43642. configurable: true
  43643. });
  43644. // Controls
  43645. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  43646. this.inputs.attachElement(element, noPreventDefault);
  43647. };
  43648. FreeCamera.prototype.detachControl = function (element) {
  43649. this.inputs.detachElement(element);
  43650. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43651. this.cameraRotation = new BABYLON.Vector2(0, 0);
  43652. };
  43653. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  43654. get: function () {
  43655. return this._collisionMask;
  43656. },
  43657. set: function (mask) {
  43658. this._collisionMask = !isNaN(mask) ? mask : -1;
  43659. },
  43660. enumerable: true,
  43661. configurable: true
  43662. });
  43663. FreeCamera.prototype._collideWithWorld = function (displacement) {
  43664. var globalPosition;
  43665. if (this.parent) {
  43666. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  43667. }
  43668. else {
  43669. globalPosition = this.position;
  43670. }
  43671. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  43672. this._oldPosition.addInPlace(this.ellipsoidOffset);
  43673. if (!this._collider) {
  43674. this._collider = new BABYLON.Collider();
  43675. }
  43676. this._collider._radius = this.ellipsoid;
  43677. this._collider.collisionMask = this._collisionMask;
  43678. //no need for clone, as long as gravity is not on.
  43679. var actualDisplacement = displacement;
  43680. //add gravity to the direction to prevent the dual-collision checking
  43681. if (this.applyGravity) {
  43682. //this prevents mending with cameraDirection, a global variable of the free camera class.
  43683. actualDisplacement = displacement.add(this.getScene().gravity);
  43684. }
  43685. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  43686. };
  43687. FreeCamera.prototype._checkInputs = function () {
  43688. if (!this._localDirection) {
  43689. this._localDirection = BABYLON.Vector3.Zero();
  43690. this._transformedDirection = BABYLON.Vector3.Zero();
  43691. }
  43692. this.inputs.checkInputs();
  43693. _super.prototype._checkInputs.call(this);
  43694. };
  43695. FreeCamera.prototype._decideIfNeedsToMove = function () {
  43696. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43697. };
  43698. FreeCamera.prototype._updatePosition = function () {
  43699. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  43700. this._collideWithWorld(this.cameraDirection);
  43701. }
  43702. else {
  43703. _super.prototype._updatePosition.call(this);
  43704. }
  43705. };
  43706. FreeCamera.prototype.dispose = function () {
  43707. this.inputs.clear();
  43708. _super.prototype.dispose.call(this);
  43709. };
  43710. FreeCamera.prototype.getClassName = function () {
  43711. return "FreeCamera";
  43712. };
  43713. __decorate([
  43714. BABYLON.serializeAsVector3()
  43715. ], FreeCamera.prototype, "ellipsoid", void 0);
  43716. __decorate([
  43717. BABYLON.serializeAsVector3()
  43718. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  43719. __decorate([
  43720. BABYLON.serialize()
  43721. ], FreeCamera.prototype, "checkCollisions", void 0);
  43722. __decorate([
  43723. BABYLON.serialize()
  43724. ], FreeCamera.prototype, "applyGravity", void 0);
  43725. return FreeCamera;
  43726. }(BABYLON.TargetCamera));
  43727. BABYLON.FreeCamera = FreeCamera;
  43728. })(BABYLON || (BABYLON = {}));
  43729. //# sourceMappingURL=babylon.freeCamera.js.map
  43730. var BABYLON;
  43731. (function (BABYLON) {
  43732. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  43733. function ArcRotateCameraKeyboardMoveInput() {
  43734. this._keys = new Array();
  43735. this.keysUp = [38];
  43736. this.keysDown = [40];
  43737. this.keysLeft = [37];
  43738. this.keysRight = [39];
  43739. this.keysReset = [220];
  43740. this.panningSensibility = 50.0;
  43741. this.zoomingSensibility = 25.0;
  43742. this.useAltToZoom = true;
  43743. }
  43744. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43745. var _this = this;
  43746. if (this._onCanvasBlurObserver) {
  43747. return;
  43748. }
  43749. this._scene = this.camera.getScene();
  43750. this._engine = this._scene.getEngine();
  43751. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43752. _this._keys = [];
  43753. });
  43754. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43755. var evt = info.event;
  43756. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43757. _this._ctrlPressed = evt.ctrlKey;
  43758. _this._altPressed = evt.altKey;
  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 === -1) {
  43766. _this._keys.push(evt.keyCode);
  43767. }
  43768. if (evt.preventDefault) {
  43769. if (!noPreventDefault) {
  43770. evt.preventDefault();
  43771. }
  43772. }
  43773. }
  43774. }
  43775. else {
  43776. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43777. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43778. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43779. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43780. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43781. var index = _this._keys.indexOf(evt.keyCode);
  43782. if (index >= 0) {
  43783. _this._keys.splice(index, 1);
  43784. }
  43785. if (evt.preventDefault) {
  43786. if (!noPreventDefault) {
  43787. evt.preventDefault();
  43788. }
  43789. }
  43790. }
  43791. }
  43792. });
  43793. };
  43794. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43795. if (this._scene) {
  43796. if (this._onKeyboardObserver) {
  43797. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43798. }
  43799. if (this._onCanvasBlurObserver) {
  43800. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43801. }
  43802. this._onKeyboardObserver = null;
  43803. this._onCanvasBlurObserver = null;
  43804. }
  43805. this._keys = [];
  43806. };
  43807. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43808. if (this._onKeyboardObserver) {
  43809. var camera = this.camera;
  43810. for (var index = 0; index < this._keys.length; index++) {
  43811. var keyCode = this._keys[index];
  43812. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43813. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43814. camera.inertialPanningX -= 1 / this.panningSensibility;
  43815. }
  43816. else {
  43817. camera.inertialAlphaOffset -= 0.01;
  43818. }
  43819. }
  43820. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43821. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43822. camera.inertialPanningY += 1 / this.panningSensibility;
  43823. }
  43824. else if (this._altPressed && this.useAltToZoom) {
  43825. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  43826. }
  43827. else {
  43828. camera.inertialBetaOffset -= 0.01;
  43829. }
  43830. }
  43831. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43832. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43833. camera.inertialPanningX += 1 / this.panningSensibility;
  43834. }
  43835. else {
  43836. camera.inertialAlphaOffset += 0.01;
  43837. }
  43838. }
  43839. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43840. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43841. camera.inertialPanningY -= 1 / this.panningSensibility;
  43842. }
  43843. else if (this._altPressed && this.useAltToZoom) {
  43844. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  43845. }
  43846. else {
  43847. camera.inertialBetaOffset += 0.01;
  43848. }
  43849. }
  43850. else if (this.keysReset.indexOf(keyCode) !== -1) {
  43851. camera.restoreState();
  43852. }
  43853. }
  43854. }
  43855. };
  43856. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  43857. return "ArcRotateCameraKeyboardMoveInput";
  43858. };
  43859. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43860. return "keyboard";
  43861. };
  43862. __decorate([
  43863. BABYLON.serialize()
  43864. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43865. __decorate([
  43866. BABYLON.serialize()
  43867. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43868. __decorate([
  43869. BABYLON.serialize()
  43870. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43871. __decorate([
  43872. BABYLON.serialize()
  43873. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43874. __decorate([
  43875. BABYLON.serialize()
  43876. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  43877. __decorate([
  43878. BABYLON.serialize()
  43879. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  43880. __decorate([
  43881. BABYLON.serialize()
  43882. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  43883. __decorate([
  43884. BABYLON.serialize()
  43885. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  43886. return ArcRotateCameraKeyboardMoveInput;
  43887. }());
  43888. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  43889. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  43890. })(BABYLON || (BABYLON = {}));
  43891. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  43892. var BABYLON;
  43893. (function (BABYLON) {
  43894. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  43895. function ArcRotateCameraMouseWheelInput() {
  43896. this.wheelPrecision = 3.0;
  43897. /**
  43898. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  43899. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  43900. */
  43901. this.wheelDeltaPercentage = 0;
  43902. }
  43903. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  43904. var _this = this;
  43905. this._wheel = function (p, s) {
  43906. //sanity check - this should be a PointerWheel event.
  43907. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  43908. return;
  43909. var event = p.event;
  43910. var delta = 0;
  43911. if (event.wheelDelta) {
  43912. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  43913. }
  43914. else if (event.detail) {
  43915. delta = -event.detail / _this.wheelPrecision;
  43916. }
  43917. if (delta)
  43918. _this.camera.inertialRadiusOffset += delta;
  43919. if (event.preventDefault) {
  43920. if (!noPreventDefault) {
  43921. event.preventDefault();
  43922. }
  43923. }
  43924. };
  43925. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  43926. };
  43927. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  43928. if (this._observer && element) {
  43929. this.camera.getScene().onPointerObservable.remove(this._observer);
  43930. this._observer = null;
  43931. this._wheel = null;
  43932. }
  43933. };
  43934. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  43935. return "ArcRotateCameraMouseWheelInput";
  43936. };
  43937. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  43938. return "mousewheel";
  43939. };
  43940. __decorate([
  43941. BABYLON.serialize()
  43942. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  43943. __decorate([
  43944. BABYLON.serialize()
  43945. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  43946. return ArcRotateCameraMouseWheelInput;
  43947. }());
  43948. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  43949. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  43950. })(BABYLON || (BABYLON = {}));
  43951. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  43952. var BABYLON;
  43953. (function (BABYLON) {
  43954. var ArcRotateCameraPointersInput = /** @class */ (function () {
  43955. function ArcRotateCameraPointersInput() {
  43956. this.buttons = [0, 1, 2];
  43957. this.angularSensibilityX = 1000.0;
  43958. this.angularSensibilityY = 1000.0;
  43959. this.pinchPrecision = 12.0;
  43960. /**
  43961. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  43962. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  43963. */
  43964. this.pinchDeltaPercentage = 0;
  43965. this.panningSensibility = 1000.0;
  43966. this.multiTouchPanning = true;
  43967. this.multiTouchPanAndZoom = true;
  43968. this._isPanClick = false;
  43969. this.pinchInwards = true;
  43970. }
  43971. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  43972. var _this = this;
  43973. var engine = this.camera.getEngine();
  43974. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  43975. var pointA = null;
  43976. var pointB = null;
  43977. var previousPinchSquaredDistance = 0;
  43978. var initialDistance = 0;
  43979. var twoFingerActivityCount = 0;
  43980. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  43981. this._pointerInput = function (p, s) {
  43982. var evt = p.event;
  43983. var isTouch = p.event.pointerType === "touch";
  43984. if (engine.isInVRExclusivePointerMode) {
  43985. return;
  43986. }
  43987. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43988. return;
  43989. }
  43990. var srcElement = (evt.srcElement || evt.target);
  43991. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43992. try {
  43993. srcElement.setPointerCapture(evt.pointerId);
  43994. }
  43995. catch (e) {
  43996. //Nothing to do with the error. Execution will continue.
  43997. }
  43998. // Manage panning with pan button click
  43999. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  44000. // manage pointers
  44001. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  44002. if (pointA === null) {
  44003. pointA = cacheSoloPointer;
  44004. }
  44005. else if (pointB === null) {
  44006. pointB = cacheSoloPointer;
  44007. }
  44008. if (!noPreventDefault) {
  44009. evt.preventDefault();
  44010. element.focus();
  44011. }
  44012. }
  44013. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  44014. _this.camera.restoreState();
  44015. }
  44016. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44017. try {
  44018. srcElement.releasePointerCapture(evt.pointerId);
  44019. }
  44020. catch (e) {
  44021. //Nothing to do with the error.
  44022. }
  44023. cacheSoloPointer = null;
  44024. previousPinchSquaredDistance = 0;
  44025. previousMultiTouchPanPosition.isPaning = false;
  44026. previousMultiTouchPanPosition.isPinching = false;
  44027. twoFingerActivityCount = 0;
  44028. initialDistance = 0;
  44029. if (!isTouch) {
  44030. pointB = null; // Mouse and pen are mono pointer
  44031. }
  44032. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  44033. //but emptying completly pointers collection is required to fix a bug on iPhone :
  44034. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  44035. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  44036. if (engine.badOS) {
  44037. pointA = pointB = null;
  44038. }
  44039. else {
  44040. //only remove the impacted pointer in case of multitouch allowing on most
  44041. //platforms switching from rotate to zoom and pan seamlessly.
  44042. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  44043. pointA = pointB;
  44044. pointB = null;
  44045. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44046. }
  44047. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  44048. pointB = null;
  44049. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44050. }
  44051. else {
  44052. pointA = pointB = null;
  44053. }
  44054. }
  44055. if (!noPreventDefault) {
  44056. evt.preventDefault();
  44057. }
  44058. }
  44059. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44060. if (!noPreventDefault) {
  44061. evt.preventDefault();
  44062. }
  44063. // One button down
  44064. if (pointA && pointB === null && cacheSoloPointer) {
  44065. if (_this.panningSensibility !== 0 &&
  44066. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  44067. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  44068. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44069. }
  44070. else {
  44071. var offsetX = evt.clientX - cacheSoloPointer.x;
  44072. var offsetY = evt.clientY - cacheSoloPointer.y;
  44073. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44074. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44075. }
  44076. cacheSoloPointer.x = evt.clientX;
  44077. cacheSoloPointer.y = evt.clientY;
  44078. }
  44079. else if (pointA && pointB) {
  44080. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44081. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44082. ed.x = evt.clientX;
  44083. ed.y = evt.clientY;
  44084. var direction = _this.pinchInwards ? 1 : -1;
  44085. var distX = pointA.x - pointB.x;
  44086. var distY = pointA.y - pointB.y;
  44087. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44088. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44089. if (previousPinchSquaredDistance === 0) {
  44090. initialDistance = pinchDistance;
  44091. previousPinchSquaredDistance = pinchSquaredDistance;
  44092. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44093. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44094. return;
  44095. }
  44096. if (_this.multiTouchPanAndZoom) {
  44097. if (_this.pinchDeltaPercentage) {
  44098. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44099. }
  44100. else {
  44101. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44102. (_this.pinchPrecision *
  44103. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44104. direction);
  44105. }
  44106. if (_this.panningSensibility !== 0) {
  44107. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44108. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44109. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44110. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44111. previousMultiTouchPanPosition.x = pointersCenterX;
  44112. previousMultiTouchPanPosition.y = pointersCenterY;
  44113. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44114. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44115. }
  44116. }
  44117. else {
  44118. twoFingerActivityCount++;
  44119. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44120. if (_this.pinchDeltaPercentage) {
  44121. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44122. }
  44123. else {
  44124. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44125. (_this.pinchPrecision *
  44126. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44127. direction);
  44128. }
  44129. previousMultiTouchPanPosition.isPaning = false;
  44130. previousMultiTouchPanPosition.isPinching = true;
  44131. }
  44132. else {
  44133. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44134. if (!previousMultiTouchPanPosition.isPaning) {
  44135. previousMultiTouchPanPosition.isPaning = true;
  44136. previousMultiTouchPanPosition.isPinching = false;
  44137. previousMultiTouchPanPosition.x = ed.x;
  44138. previousMultiTouchPanPosition.y = ed.y;
  44139. return;
  44140. }
  44141. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44142. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44143. }
  44144. }
  44145. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44146. previousMultiTouchPanPosition.x = ed.x;
  44147. previousMultiTouchPanPosition.y = ed.y;
  44148. }
  44149. }
  44150. previousPinchSquaredDistance = pinchSquaredDistance;
  44151. }
  44152. }
  44153. };
  44154. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44155. this._onContextMenu = function (evt) {
  44156. evt.preventDefault();
  44157. };
  44158. if (!this.camera._useCtrlForPanning) {
  44159. element.addEventListener("contextmenu", this._onContextMenu, false);
  44160. }
  44161. this._onLostFocus = function () {
  44162. //this._keys = [];
  44163. pointA = pointB = null;
  44164. previousPinchSquaredDistance = 0;
  44165. previousMultiTouchPanPosition.isPaning = false;
  44166. previousMultiTouchPanPosition.isPinching = false;
  44167. twoFingerActivityCount = 0;
  44168. cacheSoloPointer = null;
  44169. initialDistance = 0;
  44170. };
  44171. this._onMouseMove = function (evt) {
  44172. if (!engine.isPointerLock) {
  44173. return;
  44174. }
  44175. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44176. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44177. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44178. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44179. if (!noPreventDefault) {
  44180. evt.preventDefault();
  44181. }
  44182. };
  44183. this._onGestureStart = function (e) {
  44184. if (window.MSGesture === undefined) {
  44185. return;
  44186. }
  44187. if (!_this._MSGestureHandler) {
  44188. _this._MSGestureHandler = new MSGesture();
  44189. _this._MSGestureHandler.target = element;
  44190. }
  44191. _this._MSGestureHandler.addPointer(e.pointerId);
  44192. };
  44193. this._onGesture = function (e) {
  44194. _this.camera.radius *= e.scale;
  44195. if (e.preventDefault) {
  44196. if (!noPreventDefault) {
  44197. e.stopPropagation();
  44198. e.preventDefault();
  44199. }
  44200. }
  44201. };
  44202. element.addEventListener("mousemove", this._onMouseMove, false);
  44203. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44204. element.addEventListener("MSGestureChange", this._onGesture, false);
  44205. BABYLON.Tools.RegisterTopRootEvents([
  44206. { name: "blur", handler: this._onLostFocus }
  44207. ]);
  44208. };
  44209. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44210. if (this._onLostFocus) {
  44211. BABYLON.Tools.UnregisterTopRootEvents([
  44212. { name: "blur", handler: this._onLostFocus }
  44213. ]);
  44214. }
  44215. if (element && this._observer) {
  44216. this.camera.getScene().onPointerObservable.remove(this._observer);
  44217. this._observer = null;
  44218. if (this._onContextMenu) {
  44219. element.removeEventListener("contextmenu", this._onContextMenu);
  44220. }
  44221. if (this._onMouseMove) {
  44222. element.removeEventListener("mousemove", this._onMouseMove);
  44223. }
  44224. if (this._onGestureStart) {
  44225. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44226. }
  44227. if (this._onGesture) {
  44228. element.removeEventListener("MSGestureChange", this._onGesture);
  44229. }
  44230. this._isPanClick = false;
  44231. this.pinchInwards = true;
  44232. this._onMouseMove = null;
  44233. this._onGestureStart = null;
  44234. this._onGesture = null;
  44235. this._MSGestureHandler = null;
  44236. this._onLostFocus = null;
  44237. this._onContextMenu = null;
  44238. }
  44239. };
  44240. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  44241. return "ArcRotateCameraPointersInput";
  44242. };
  44243. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  44244. return "pointers";
  44245. };
  44246. __decorate([
  44247. BABYLON.serialize()
  44248. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  44249. __decorate([
  44250. BABYLON.serialize()
  44251. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  44252. __decorate([
  44253. BABYLON.serialize()
  44254. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  44255. __decorate([
  44256. BABYLON.serialize()
  44257. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  44258. __decorate([
  44259. BABYLON.serialize()
  44260. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  44261. __decorate([
  44262. BABYLON.serialize()
  44263. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  44264. __decorate([
  44265. BABYLON.serialize()
  44266. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  44267. __decorate([
  44268. BABYLON.serialize()
  44269. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  44270. return ArcRotateCameraPointersInput;
  44271. }());
  44272. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  44273. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  44274. })(BABYLON || (BABYLON = {}));
  44275. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  44276. var BABYLON;
  44277. (function (BABYLON) {
  44278. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  44279. __extends(ArcRotateCameraInputsManager, _super);
  44280. function ArcRotateCameraInputsManager(camera) {
  44281. return _super.call(this, camera) || this;
  44282. }
  44283. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  44284. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  44285. return this;
  44286. };
  44287. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  44288. this.add(new BABYLON.ArcRotateCameraPointersInput());
  44289. return this;
  44290. };
  44291. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  44292. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  44293. return this;
  44294. };
  44295. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  44296. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  44297. return this;
  44298. };
  44299. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  44300. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  44301. return this;
  44302. };
  44303. return ArcRotateCameraInputsManager;
  44304. }(BABYLON.CameraInputsManager));
  44305. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  44306. })(BABYLON || (BABYLON = {}));
  44307. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  44308. var BABYLON;
  44309. (function (BABYLON) {
  44310. var ArcRotateCamera = /** @class */ (function (_super) {
  44311. __extends(ArcRotateCamera, _super);
  44312. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  44313. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  44314. _this.inertialAlphaOffset = 0;
  44315. _this.inertialBetaOffset = 0;
  44316. _this.inertialRadiusOffset = 0;
  44317. _this.lowerAlphaLimit = null;
  44318. _this.upperAlphaLimit = null;
  44319. _this.lowerBetaLimit = 0.01;
  44320. _this.upperBetaLimit = Math.PI;
  44321. _this.lowerRadiusLimit = null;
  44322. _this.upperRadiusLimit = null;
  44323. _this.inertialPanningX = 0;
  44324. _this.inertialPanningY = 0;
  44325. _this.pinchToPanMaxDistance = 20;
  44326. _this.panningDistanceLimit = null;
  44327. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  44328. _this.panningInertia = 0.9;
  44329. //-- end properties for backward compatibility for inputs
  44330. _this.zoomOnFactor = 1;
  44331. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  44332. _this.allowUpsideDown = true;
  44333. _this._viewMatrix = new BABYLON.Matrix();
  44334. // Panning
  44335. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  44336. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  44337. _this.checkCollisions = false;
  44338. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44339. _this._previousPosition = BABYLON.Vector3.Zero();
  44340. _this._collisionVelocity = BABYLON.Vector3.Zero();
  44341. _this._newPosition = BABYLON.Vector3.Zero();
  44342. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44343. if (collidedMesh === void 0) { collidedMesh = null; }
  44344. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  44345. newPosition.multiplyInPlace(_this._collider._radius);
  44346. }
  44347. if (!collidedMesh) {
  44348. _this._previousPosition.copyFrom(_this.position);
  44349. }
  44350. else {
  44351. _this.setPosition(newPosition);
  44352. if (_this.onCollide) {
  44353. _this.onCollide(collidedMesh);
  44354. }
  44355. }
  44356. // Recompute because of constraints
  44357. var cosa = Math.cos(_this.alpha);
  44358. var sina = Math.sin(_this.alpha);
  44359. var cosb = Math.cos(_this.beta);
  44360. var sinb = Math.sin(_this.beta);
  44361. if (sinb === 0) {
  44362. sinb = 0.0001;
  44363. }
  44364. var target = _this._getTargetPosition();
  44365. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  44366. _this.position.copyFrom(_this._newPosition);
  44367. var up = _this.upVector;
  44368. if (_this.allowUpsideDown && _this.beta < 0) {
  44369. up = up.clone();
  44370. up = up.negate();
  44371. }
  44372. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  44373. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  44374. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  44375. _this._collisionTriggered = false;
  44376. };
  44377. _this._target = BABYLON.Vector3.Zero();
  44378. if (target) {
  44379. _this.setTarget(target);
  44380. }
  44381. _this.alpha = alpha;
  44382. _this.beta = beta;
  44383. _this.radius = radius;
  44384. _this.getViewMatrix();
  44385. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  44386. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  44387. return _this;
  44388. }
  44389. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  44390. get: function () {
  44391. return this._target;
  44392. },
  44393. set: function (value) {
  44394. this.setTarget(value);
  44395. },
  44396. enumerable: true,
  44397. configurable: true
  44398. });
  44399. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  44400. //-- begin properties for backward compatibility for inputs
  44401. get: function () {
  44402. var pointers = this.inputs.attached["pointers"];
  44403. if (pointers)
  44404. return pointers.angularSensibilityX;
  44405. return 0;
  44406. },
  44407. set: function (value) {
  44408. var pointers = this.inputs.attached["pointers"];
  44409. if (pointers) {
  44410. pointers.angularSensibilityX = value;
  44411. }
  44412. },
  44413. enumerable: true,
  44414. configurable: true
  44415. });
  44416. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  44417. get: function () {
  44418. var pointers = this.inputs.attached["pointers"];
  44419. if (pointers)
  44420. return pointers.angularSensibilityY;
  44421. return 0;
  44422. },
  44423. set: function (value) {
  44424. var pointers = this.inputs.attached["pointers"];
  44425. if (pointers) {
  44426. pointers.angularSensibilityY = value;
  44427. }
  44428. },
  44429. enumerable: true,
  44430. configurable: true
  44431. });
  44432. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  44433. get: function () {
  44434. var pointers = this.inputs.attached["pointers"];
  44435. if (pointers)
  44436. return pointers.pinchPrecision;
  44437. return 0;
  44438. },
  44439. set: function (value) {
  44440. var pointers = this.inputs.attached["pointers"];
  44441. if (pointers) {
  44442. pointers.pinchPrecision = value;
  44443. }
  44444. },
  44445. enumerable: true,
  44446. configurable: true
  44447. });
  44448. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  44449. get: function () {
  44450. var pointers = this.inputs.attached["pointers"];
  44451. if (pointers)
  44452. return pointers.pinchDeltaPercentage;
  44453. return 0;
  44454. },
  44455. set: function (value) {
  44456. var pointers = this.inputs.attached["pointers"];
  44457. if (pointers) {
  44458. pointers.pinchDeltaPercentage = value;
  44459. }
  44460. },
  44461. enumerable: true,
  44462. configurable: true
  44463. });
  44464. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  44465. get: function () {
  44466. var pointers = this.inputs.attached["pointers"];
  44467. if (pointers)
  44468. return pointers.panningSensibility;
  44469. return 0;
  44470. },
  44471. set: function (value) {
  44472. var pointers = this.inputs.attached["pointers"];
  44473. if (pointers) {
  44474. pointers.panningSensibility = value;
  44475. }
  44476. },
  44477. enumerable: true,
  44478. configurable: true
  44479. });
  44480. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  44481. get: function () {
  44482. var keyboard = this.inputs.attached["keyboard"];
  44483. if (keyboard)
  44484. return keyboard.keysUp;
  44485. return [];
  44486. },
  44487. set: function (value) {
  44488. var keyboard = this.inputs.attached["keyboard"];
  44489. if (keyboard)
  44490. keyboard.keysUp = value;
  44491. },
  44492. enumerable: true,
  44493. configurable: true
  44494. });
  44495. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  44496. get: function () {
  44497. var keyboard = this.inputs.attached["keyboard"];
  44498. if (keyboard)
  44499. return keyboard.keysDown;
  44500. return [];
  44501. },
  44502. set: function (value) {
  44503. var keyboard = this.inputs.attached["keyboard"];
  44504. if (keyboard)
  44505. keyboard.keysDown = value;
  44506. },
  44507. enumerable: true,
  44508. configurable: true
  44509. });
  44510. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  44511. get: function () {
  44512. var keyboard = this.inputs.attached["keyboard"];
  44513. if (keyboard)
  44514. return keyboard.keysLeft;
  44515. return [];
  44516. },
  44517. set: function (value) {
  44518. var keyboard = this.inputs.attached["keyboard"];
  44519. if (keyboard)
  44520. keyboard.keysLeft = value;
  44521. },
  44522. enumerable: true,
  44523. configurable: true
  44524. });
  44525. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  44526. get: function () {
  44527. var keyboard = this.inputs.attached["keyboard"];
  44528. if (keyboard)
  44529. return keyboard.keysRight;
  44530. return [];
  44531. },
  44532. set: function (value) {
  44533. var keyboard = this.inputs.attached["keyboard"];
  44534. if (keyboard)
  44535. keyboard.keysRight = value;
  44536. },
  44537. enumerable: true,
  44538. configurable: true
  44539. });
  44540. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  44541. get: function () {
  44542. var mousewheel = this.inputs.attached["mousewheel"];
  44543. if (mousewheel)
  44544. return mousewheel.wheelPrecision;
  44545. return 0;
  44546. },
  44547. set: function (value) {
  44548. var mousewheel = this.inputs.attached["mousewheel"];
  44549. if (mousewheel)
  44550. mousewheel.wheelPrecision = value;
  44551. },
  44552. enumerable: true,
  44553. configurable: true
  44554. });
  44555. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  44556. get: function () {
  44557. var mousewheel = this.inputs.attached["mousewheel"];
  44558. if (mousewheel)
  44559. return mousewheel.wheelDeltaPercentage;
  44560. return 0;
  44561. },
  44562. set: function (value) {
  44563. var mousewheel = this.inputs.attached["mousewheel"];
  44564. if (mousewheel)
  44565. mousewheel.wheelDeltaPercentage = value;
  44566. },
  44567. enumerable: true,
  44568. configurable: true
  44569. });
  44570. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  44571. get: function () {
  44572. return this._bouncingBehavior;
  44573. },
  44574. enumerable: true,
  44575. configurable: true
  44576. });
  44577. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  44578. get: function () {
  44579. return this._bouncingBehavior != null;
  44580. },
  44581. set: function (value) {
  44582. if (value === this.useBouncingBehavior) {
  44583. return;
  44584. }
  44585. if (value) {
  44586. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  44587. this.addBehavior(this._bouncingBehavior);
  44588. }
  44589. else if (this._bouncingBehavior) {
  44590. this.removeBehavior(this._bouncingBehavior);
  44591. this._bouncingBehavior = null;
  44592. }
  44593. },
  44594. enumerable: true,
  44595. configurable: true
  44596. });
  44597. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  44598. get: function () {
  44599. return this._framingBehavior;
  44600. },
  44601. enumerable: true,
  44602. configurable: true
  44603. });
  44604. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  44605. get: function () {
  44606. return this._framingBehavior != null;
  44607. },
  44608. set: function (value) {
  44609. if (value === this.useFramingBehavior) {
  44610. return;
  44611. }
  44612. if (value) {
  44613. this._framingBehavior = new BABYLON.FramingBehavior();
  44614. this.addBehavior(this._framingBehavior);
  44615. }
  44616. else if (this._framingBehavior) {
  44617. this.removeBehavior(this._framingBehavior);
  44618. this._framingBehavior = null;
  44619. }
  44620. },
  44621. enumerable: true,
  44622. configurable: true
  44623. });
  44624. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  44625. get: function () {
  44626. return this._autoRotationBehavior;
  44627. },
  44628. enumerable: true,
  44629. configurable: true
  44630. });
  44631. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  44632. get: function () {
  44633. return this._autoRotationBehavior != null;
  44634. },
  44635. set: function (value) {
  44636. if (value === this.useAutoRotationBehavior) {
  44637. return;
  44638. }
  44639. if (value) {
  44640. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  44641. this.addBehavior(this._autoRotationBehavior);
  44642. }
  44643. else if (this._autoRotationBehavior) {
  44644. this.removeBehavior(this._autoRotationBehavior);
  44645. this._autoRotationBehavior = null;
  44646. }
  44647. },
  44648. enumerable: true,
  44649. configurable: true
  44650. });
  44651. // Cache
  44652. ArcRotateCamera.prototype._initCache = function () {
  44653. _super.prototype._initCache.call(this);
  44654. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  44655. this._cache.alpha = undefined;
  44656. this._cache.beta = undefined;
  44657. this._cache.radius = undefined;
  44658. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  44659. };
  44660. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  44661. if (!ignoreParentClass) {
  44662. _super.prototype._updateCache.call(this);
  44663. }
  44664. this._cache._target.copyFrom(this._getTargetPosition());
  44665. this._cache.alpha = this.alpha;
  44666. this._cache.beta = this.beta;
  44667. this._cache.radius = this.radius;
  44668. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  44669. };
  44670. ArcRotateCamera.prototype._getTargetPosition = function () {
  44671. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  44672. var pos = this._targetHost.getAbsolutePosition();
  44673. if (this._targetBoundingCenter) {
  44674. pos.addToRef(this._targetBoundingCenter, this._target);
  44675. }
  44676. else {
  44677. this._target.copyFrom(pos);
  44678. }
  44679. }
  44680. var lockedTargetPosition = this._getLockedTargetPosition();
  44681. if (lockedTargetPosition) {
  44682. return lockedTargetPosition;
  44683. }
  44684. return this._target;
  44685. };
  44686. ArcRotateCamera.prototype.storeState = function () {
  44687. this._storedAlpha = this.alpha;
  44688. this._storedBeta = this.beta;
  44689. this._storedRadius = this.radius;
  44690. this._storedTarget = this._getTargetPosition().clone();
  44691. return _super.prototype.storeState.call(this);
  44692. };
  44693. /**
  44694. * Restored camera state. You must call storeState() first
  44695. */
  44696. ArcRotateCamera.prototype._restoreStateValues = function () {
  44697. if (!_super.prototype._restoreStateValues.call(this)) {
  44698. return false;
  44699. }
  44700. this.alpha = this._storedAlpha;
  44701. this.beta = this._storedBeta;
  44702. this.radius = this._storedRadius;
  44703. this.setTarget(this._storedTarget.clone());
  44704. this.inertialAlphaOffset = 0;
  44705. this.inertialBetaOffset = 0;
  44706. this.inertialRadiusOffset = 0;
  44707. this.inertialPanningX = 0;
  44708. this.inertialPanningY = 0;
  44709. return true;
  44710. };
  44711. // Synchronized
  44712. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  44713. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  44714. return false;
  44715. return this._cache._target.equals(this._getTargetPosition())
  44716. && this._cache.alpha === this.alpha
  44717. && this._cache.beta === this.beta
  44718. && this._cache.radius === this.radius
  44719. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  44720. };
  44721. // Methods
  44722. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  44723. var _this = this;
  44724. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  44725. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  44726. this._useCtrlForPanning = useCtrlForPanning;
  44727. this._panningMouseButton = panningMouseButton;
  44728. this.inputs.attachElement(element, noPreventDefault);
  44729. this._reset = function () {
  44730. _this.inertialAlphaOffset = 0;
  44731. _this.inertialBetaOffset = 0;
  44732. _this.inertialRadiusOffset = 0;
  44733. _this.inertialPanningX = 0;
  44734. _this.inertialPanningY = 0;
  44735. };
  44736. };
  44737. ArcRotateCamera.prototype.detachControl = function (element) {
  44738. this.inputs.detachElement(element);
  44739. if (this._reset) {
  44740. this._reset();
  44741. }
  44742. };
  44743. ArcRotateCamera.prototype._checkInputs = function () {
  44744. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  44745. if (this._collisionTriggered) {
  44746. return;
  44747. }
  44748. this.inputs.checkInputs();
  44749. // Inertia
  44750. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  44751. if (this.getScene().useRightHandedSystem) {
  44752. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44753. }
  44754. else {
  44755. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44756. }
  44757. this.beta += this.inertialBetaOffset;
  44758. this.radius -= this.inertialRadiusOffset;
  44759. this.inertialAlphaOffset *= this.inertia;
  44760. this.inertialBetaOffset *= this.inertia;
  44761. this.inertialRadiusOffset *= this.inertia;
  44762. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  44763. this.inertialAlphaOffset = 0;
  44764. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  44765. this.inertialBetaOffset = 0;
  44766. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  44767. this.inertialRadiusOffset = 0;
  44768. }
  44769. // Panning inertia
  44770. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  44771. if (!this._localDirection) {
  44772. this._localDirection = BABYLON.Vector3.Zero();
  44773. this._transformedDirection = BABYLON.Vector3.Zero();
  44774. }
  44775. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  44776. this._localDirection.multiplyInPlace(this.panningAxis);
  44777. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  44778. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  44779. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  44780. if (!this.panningAxis.y) {
  44781. this._transformedDirection.y = 0;
  44782. }
  44783. if (!this._targetHost) {
  44784. if (this.panningDistanceLimit) {
  44785. this._transformedDirection.addInPlace(this._target);
  44786. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  44787. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  44788. this._target.copyFrom(this._transformedDirection);
  44789. }
  44790. }
  44791. else {
  44792. this._target.addInPlace(this._transformedDirection);
  44793. }
  44794. }
  44795. this.inertialPanningX *= this.panningInertia;
  44796. this.inertialPanningY *= this.panningInertia;
  44797. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  44798. this.inertialPanningX = 0;
  44799. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  44800. this.inertialPanningY = 0;
  44801. }
  44802. // Limits
  44803. this._checkLimits();
  44804. _super.prototype._checkInputs.call(this);
  44805. };
  44806. ArcRotateCamera.prototype._checkLimits = function () {
  44807. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  44808. if (this.allowUpsideDown && this.beta > Math.PI) {
  44809. this.beta = this.beta - (2 * Math.PI);
  44810. }
  44811. }
  44812. else {
  44813. if (this.beta < this.lowerBetaLimit) {
  44814. this.beta = this.lowerBetaLimit;
  44815. }
  44816. }
  44817. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  44818. if (this.allowUpsideDown && this.beta < -Math.PI) {
  44819. this.beta = this.beta + (2 * Math.PI);
  44820. }
  44821. }
  44822. else {
  44823. if (this.beta > this.upperBetaLimit) {
  44824. this.beta = this.upperBetaLimit;
  44825. }
  44826. }
  44827. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  44828. this.alpha = this.lowerAlphaLimit;
  44829. }
  44830. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  44831. this.alpha = this.upperAlphaLimit;
  44832. }
  44833. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  44834. this.radius = this.lowerRadiusLimit;
  44835. }
  44836. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  44837. this.radius = this.upperRadiusLimit;
  44838. }
  44839. };
  44840. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  44841. var radiusv3 = this.position.subtract(this._getTargetPosition());
  44842. this.radius = radiusv3.length();
  44843. if (this.radius === 0) {
  44844. this.radius = 0.0001; // Just to avoid division by zero
  44845. }
  44846. // Alpha
  44847. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  44848. if (radiusv3.z < 0) {
  44849. this.alpha = 2 * Math.PI - this.alpha;
  44850. }
  44851. // Beta
  44852. this.beta = Math.acos(radiusv3.y / this.radius);
  44853. this._checkLimits();
  44854. };
  44855. ArcRotateCamera.prototype.setPosition = function (position) {
  44856. if (this.position.equals(position)) {
  44857. return;
  44858. }
  44859. this.position.copyFrom(position);
  44860. this.rebuildAnglesAndRadius();
  44861. };
  44862. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  44863. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  44864. if (allowSamePosition === void 0) { allowSamePosition = false; }
  44865. if (target.getBoundingInfo) {
  44866. if (toBoundingCenter) {
  44867. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  44868. }
  44869. else {
  44870. this._targetBoundingCenter = null;
  44871. }
  44872. this._targetHost = target;
  44873. this._target = this._getTargetPosition();
  44874. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  44875. }
  44876. else {
  44877. var newTarget = target;
  44878. var currentTarget = this._getTargetPosition();
  44879. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  44880. return;
  44881. }
  44882. this._targetHost = null;
  44883. this._target = newTarget;
  44884. this._targetBoundingCenter = null;
  44885. this.onMeshTargetChangedObservable.notifyObservers(null);
  44886. }
  44887. this.rebuildAnglesAndRadius();
  44888. };
  44889. ArcRotateCamera.prototype._getViewMatrix = function () {
  44890. // Compute
  44891. var cosa = Math.cos(this.alpha);
  44892. var sina = Math.sin(this.alpha);
  44893. var cosb = Math.cos(this.beta);
  44894. var sinb = Math.sin(this.beta);
  44895. if (sinb === 0) {
  44896. sinb = 0.0001;
  44897. }
  44898. var target = this._getTargetPosition();
  44899. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  44900. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  44901. if (!this._collider) {
  44902. this._collider = new BABYLON.Collider();
  44903. }
  44904. this._collider._radius = this.collisionRadius;
  44905. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  44906. this._collisionTriggered = true;
  44907. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44908. }
  44909. else {
  44910. this.position.copyFrom(this._newPosition);
  44911. var up = this.upVector;
  44912. if (this.allowUpsideDown && sinb < 0) {
  44913. up = up.clone();
  44914. up = up.negate();
  44915. }
  44916. if (this.getScene().useRightHandedSystem) {
  44917. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  44918. }
  44919. else {
  44920. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  44921. }
  44922. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  44923. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  44924. }
  44925. this._currentTarget = target;
  44926. return this._viewMatrix;
  44927. };
  44928. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  44929. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44930. meshes = meshes || this.getScene().meshes;
  44931. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  44932. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  44933. this.radius = distance * this.zoomOnFactor;
  44934. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  44935. };
  44936. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  44937. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44938. var meshesOrMinMaxVector;
  44939. var distance;
  44940. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  44941. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  44942. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  44943. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  44944. }
  44945. else {
  44946. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  44947. meshesOrMinMaxVector = minMaxVectorAndDistance;
  44948. distance = minMaxVectorAndDistance.distance;
  44949. }
  44950. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  44951. if (!doNotUpdateMaxZ) {
  44952. this.maxZ = distance * 2;
  44953. }
  44954. };
  44955. /**
  44956. * @override
  44957. * Override Camera.createRigCamera
  44958. */
  44959. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  44960. var alphaShift = 0;
  44961. switch (this.cameraRigMode) {
  44962. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44963. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44964. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44965. case BABYLON.Camera.RIG_MODE_VR:
  44966. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  44967. break;
  44968. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44969. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  44970. break;
  44971. }
  44972. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  44973. rigCam._cameraRigParams = {};
  44974. return rigCam;
  44975. };
  44976. /**
  44977. * @override
  44978. * Override Camera._updateRigCameras
  44979. */
  44980. ArcRotateCamera.prototype._updateRigCameras = function () {
  44981. var camLeft = this._rigCameras[0];
  44982. var camRight = this._rigCameras[1];
  44983. camLeft.beta = camRight.beta = this.beta;
  44984. camLeft.radius = camRight.radius = this.radius;
  44985. switch (this.cameraRigMode) {
  44986. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44987. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44988. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44989. case BABYLON.Camera.RIG_MODE_VR:
  44990. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44991. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44992. break;
  44993. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44994. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44995. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44996. break;
  44997. }
  44998. _super.prototype._updateRigCameras.call(this);
  44999. };
  45000. ArcRotateCamera.prototype.dispose = function () {
  45001. this.inputs.clear();
  45002. _super.prototype.dispose.call(this);
  45003. };
  45004. ArcRotateCamera.prototype.getClassName = function () {
  45005. return "ArcRotateCamera";
  45006. };
  45007. __decorate([
  45008. BABYLON.serialize()
  45009. ], ArcRotateCamera.prototype, "alpha", void 0);
  45010. __decorate([
  45011. BABYLON.serialize()
  45012. ], ArcRotateCamera.prototype, "beta", void 0);
  45013. __decorate([
  45014. BABYLON.serialize()
  45015. ], ArcRotateCamera.prototype, "radius", void 0);
  45016. __decorate([
  45017. BABYLON.serializeAsVector3("target")
  45018. ], ArcRotateCamera.prototype, "_target", void 0);
  45019. __decorate([
  45020. BABYLON.serialize()
  45021. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  45022. __decorate([
  45023. BABYLON.serialize()
  45024. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  45025. __decorate([
  45026. BABYLON.serialize()
  45027. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  45028. __decorate([
  45029. BABYLON.serialize()
  45030. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  45031. __decorate([
  45032. BABYLON.serialize()
  45033. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  45034. __decorate([
  45035. BABYLON.serialize()
  45036. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  45037. __decorate([
  45038. BABYLON.serialize()
  45039. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  45040. __decorate([
  45041. BABYLON.serialize()
  45042. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  45043. __decorate([
  45044. BABYLON.serialize()
  45045. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  45046. __decorate([
  45047. BABYLON.serialize()
  45048. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  45049. __decorate([
  45050. BABYLON.serialize()
  45051. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  45052. __decorate([
  45053. BABYLON.serialize()
  45054. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  45055. __decorate([
  45056. BABYLON.serialize()
  45057. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  45058. __decorate([
  45059. BABYLON.serializeAsVector3()
  45060. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  45061. __decorate([
  45062. BABYLON.serialize()
  45063. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  45064. __decorate([
  45065. BABYLON.serialize()
  45066. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  45067. __decorate([
  45068. BABYLON.serialize()
  45069. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45070. return ArcRotateCamera;
  45071. }(BABYLON.TargetCamera));
  45072. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45073. })(BABYLON || (BABYLON = {}));
  45074. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45075. var BABYLON;
  45076. (function (BABYLON) {
  45077. /**
  45078. * The HemisphericLight simulates the ambient environment light,
  45079. * so the passed direction is the light reflection direction, not the incoming direction.
  45080. */
  45081. var HemisphericLight = /** @class */ (function (_super) {
  45082. __extends(HemisphericLight, _super);
  45083. /**
  45084. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45085. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45086. * The HemisphericLight can't cast shadows.
  45087. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45088. * @param name The friendly name of the light
  45089. * @param direction The direction of the light reflection
  45090. * @param scene The scene the light belongs to
  45091. */
  45092. function HemisphericLight(name, direction, scene) {
  45093. var _this = _super.call(this, name, scene) || this;
  45094. /**
  45095. * The groundColor is the light in the opposite direction to the one specified during creation.
  45096. * 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.
  45097. */
  45098. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45099. _this.direction = direction || BABYLON.Vector3.Up();
  45100. return _this;
  45101. }
  45102. HemisphericLight.prototype._buildUniformLayout = function () {
  45103. this._uniformBuffer.addUniform("vLightData", 4);
  45104. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45105. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45106. this._uniformBuffer.addUniform("vLightGround", 3);
  45107. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45108. this._uniformBuffer.addUniform("depthValues", 2);
  45109. this._uniformBuffer.create();
  45110. };
  45111. /**
  45112. * Returns the string "HemisphericLight".
  45113. * @return The class name
  45114. */
  45115. HemisphericLight.prototype.getClassName = function () {
  45116. return "HemisphericLight";
  45117. };
  45118. /**
  45119. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45120. * Returns the updated direction.
  45121. * @param target The target the direction should point to
  45122. * @return The computed direction
  45123. */
  45124. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45125. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45126. return this.direction;
  45127. };
  45128. /**
  45129. * Returns the shadow generator associated to the light.
  45130. * @returns Always null for hemispheric lights because it does not support shadows.
  45131. */
  45132. HemisphericLight.prototype.getShadowGenerator = function () {
  45133. return null;
  45134. };
  45135. /**
  45136. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45137. * @param effect The effect to update
  45138. * @param lightIndex The index of the light in the effect to update
  45139. * @returns The hemispheric light
  45140. */
  45141. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45142. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45143. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45144. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45145. return this;
  45146. };
  45147. /**
  45148. * @ignore internal use only.
  45149. */
  45150. HemisphericLight.prototype._getWorldMatrix = function () {
  45151. if (!this._worldMatrix) {
  45152. this._worldMatrix = BABYLON.Matrix.Identity();
  45153. }
  45154. return this._worldMatrix;
  45155. };
  45156. /**
  45157. * Returns the integer 3.
  45158. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45159. */
  45160. HemisphericLight.prototype.getTypeID = function () {
  45161. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45162. };
  45163. __decorate([
  45164. BABYLON.serializeAsColor3()
  45165. ], HemisphericLight.prototype, "groundColor", void 0);
  45166. __decorate([
  45167. BABYLON.serializeAsVector3()
  45168. ], HemisphericLight.prototype, "direction", void 0);
  45169. return HemisphericLight;
  45170. }(BABYLON.Light));
  45171. BABYLON.HemisphericLight = HemisphericLight;
  45172. })(BABYLON || (BABYLON = {}));
  45173. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45174. var BABYLON;
  45175. (function (BABYLON) {
  45176. /**
  45177. * Base implementation of @see IShadowLight
  45178. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45179. */
  45180. var ShadowLight = /** @class */ (function (_super) {
  45181. __extends(ShadowLight, _super);
  45182. function ShadowLight() {
  45183. var _this = _super !== null && _super.apply(this, arguments) || this;
  45184. _this._needProjectionMatrixCompute = true;
  45185. return _this;
  45186. }
  45187. ShadowLight.prototype._setPosition = function (value) {
  45188. this._position = value;
  45189. };
  45190. Object.defineProperty(ShadowLight.prototype, "position", {
  45191. /**
  45192. * Sets the position the shadow will be casted from. Also use as the light position for both
  45193. * point and spot lights.
  45194. */
  45195. get: function () {
  45196. return this._position;
  45197. },
  45198. /**
  45199. * Sets the position the shadow will be casted from. Also use as the light position for both
  45200. * point and spot lights.
  45201. */
  45202. set: function (value) {
  45203. this._setPosition(value);
  45204. },
  45205. enumerable: true,
  45206. configurable: true
  45207. });
  45208. ShadowLight.prototype._setDirection = function (value) {
  45209. this._direction = value;
  45210. };
  45211. Object.defineProperty(ShadowLight.prototype, "direction", {
  45212. /**
  45213. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45214. * Also use as the light direction on spot and directional lights.
  45215. */
  45216. get: function () {
  45217. return this._direction;
  45218. },
  45219. /**
  45220. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45221. * Also use as the light direction on spot and directional lights.
  45222. */
  45223. set: function (value) {
  45224. this._setDirection(value);
  45225. },
  45226. enumerable: true,
  45227. configurable: true
  45228. });
  45229. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  45230. /**
  45231. * Gets the shadow projection clipping minimum z value.
  45232. */
  45233. get: function () {
  45234. return this._shadowMinZ;
  45235. },
  45236. /**
  45237. * Sets the shadow projection clipping minimum z value.
  45238. */
  45239. set: function (value) {
  45240. this._shadowMinZ = value;
  45241. this.forceProjectionMatrixCompute();
  45242. },
  45243. enumerable: true,
  45244. configurable: true
  45245. });
  45246. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  45247. /**
  45248. * Sets the shadow projection clipping maximum z value.
  45249. */
  45250. get: function () {
  45251. return this._shadowMaxZ;
  45252. },
  45253. /**
  45254. * Gets the shadow projection clipping maximum z value.
  45255. */
  45256. set: function (value) {
  45257. this._shadowMaxZ = value;
  45258. this.forceProjectionMatrixCompute();
  45259. },
  45260. enumerable: true,
  45261. configurable: true
  45262. });
  45263. /**
  45264. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  45265. * @returns true if the information has been computed, false if it does not need to (no parenting)
  45266. */
  45267. ShadowLight.prototype.computeTransformedInformation = function () {
  45268. if (this.parent && this.parent.getWorldMatrix) {
  45269. if (!this.transformedPosition) {
  45270. this.transformedPosition = BABYLON.Vector3.Zero();
  45271. }
  45272. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  45273. // In case the direction is present.
  45274. if (this.direction) {
  45275. if (!this.transformedDirection) {
  45276. this.transformedDirection = BABYLON.Vector3.Zero();
  45277. }
  45278. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  45279. }
  45280. return true;
  45281. }
  45282. return false;
  45283. };
  45284. /**
  45285. * Return the depth scale used for the shadow map.
  45286. * @returns the depth scale.
  45287. */
  45288. ShadowLight.prototype.getDepthScale = function () {
  45289. return 50.0;
  45290. };
  45291. /**
  45292. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  45293. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45294. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45295. */
  45296. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  45297. return this.transformedDirection ? this.transformedDirection : this.direction;
  45298. };
  45299. /**
  45300. * Returns the ShadowLight absolute position in the World.
  45301. * @returns the position vector in world space
  45302. */
  45303. ShadowLight.prototype.getAbsolutePosition = function () {
  45304. return this.transformedPosition ? this.transformedPosition : this.position;
  45305. };
  45306. /**
  45307. * Sets the ShadowLight direction toward the passed target.
  45308. * @param target The point tot target in local space
  45309. * @returns the updated ShadowLight direction
  45310. */
  45311. ShadowLight.prototype.setDirectionToTarget = function (target) {
  45312. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  45313. return this.direction;
  45314. };
  45315. /**
  45316. * Returns the light rotation in euler definition.
  45317. * @returns the x y z rotation in local space.
  45318. */
  45319. ShadowLight.prototype.getRotation = function () {
  45320. this.direction.normalize();
  45321. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  45322. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  45323. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  45324. };
  45325. /**
  45326. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  45327. * @returns true if a cube texture needs to be use
  45328. */
  45329. ShadowLight.prototype.needCube = function () {
  45330. return false;
  45331. };
  45332. /**
  45333. * Detects if the projection matrix requires to be recomputed this frame.
  45334. * @returns true if it requires to be recomputed otherwise, false.
  45335. */
  45336. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  45337. return this._needProjectionMatrixCompute;
  45338. };
  45339. /**
  45340. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  45341. */
  45342. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  45343. this._needProjectionMatrixCompute = true;
  45344. };
  45345. /**
  45346. * Get the world matrix of the sahdow lights.
  45347. * @ignore Internal Use Only
  45348. */
  45349. ShadowLight.prototype._getWorldMatrix = function () {
  45350. if (!this._worldMatrix) {
  45351. this._worldMatrix = BABYLON.Matrix.Identity();
  45352. }
  45353. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  45354. return this._worldMatrix;
  45355. };
  45356. /**
  45357. * Gets the minZ used for shadow according to both the scene and the light.
  45358. * @param activeCamera The camera we are returning the min for
  45359. * @returns the depth min z
  45360. */
  45361. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  45362. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  45363. };
  45364. /**
  45365. * Gets the maxZ used for shadow according to both the scene and the light.
  45366. * @param activeCamera The camera we are returning the max for
  45367. * @returns the depth max z
  45368. */
  45369. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  45370. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  45371. };
  45372. /**
  45373. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  45374. * @param matrix The materix to updated with the projection information
  45375. * @param viewMatrix The transform matrix of the light
  45376. * @param renderList The list of mesh to render in the map
  45377. * @returns The current light
  45378. */
  45379. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45380. if (this.customProjectionMatrixBuilder) {
  45381. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  45382. }
  45383. else {
  45384. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45385. }
  45386. return this;
  45387. };
  45388. __decorate([
  45389. BABYLON.serializeAsVector3()
  45390. ], ShadowLight.prototype, "position", null);
  45391. __decorate([
  45392. BABYLON.serializeAsVector3()
  45393. ], ShadowLight.prototype, "direction", null);
  45394. __decorate([
  45395. BABYLON.serialize()
  45396. ], ShadowLight.prototype, "shadowMinZ", null);
  45397. __decorate([
  45398. BABYLON.serialize()
  45399. ], ShadowLight.prototype, "shadowMaxZ", null);
  45400. return ShadowLight;
  45401. }(BABYLON.Light));
  45402. BABYLON.ShadowLight = ShadowLight;
  45403. })(BABYLON || (BABYLON = {}));
  45404. //# sourceMappingURL=babylon.shadowLight.js.map
  45405. var BABYLON;
  45406. (function (BABYLON) {
  45407. /**
  45408. * A point light is a light defined by an unique point in world space.
  45409. * The light is emitted in every direction from this point.
  45410. * A good example of a point light is a standard light bulb.
  45411. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45412. */
  45413. var PointLight = /** @class */ (function (_super) {
  45414. __extends(PointLight, _super);
  45415. /**
  45416. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  45417. * A PointLight emits the light in every direction.
  45418. * It can cast shadows.
  45419. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  45420. * ```javascript
  45421. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  45422. * ```
  45423. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45424. * @param name The light friendly name
  45425. * @param position The position of the point light in the scene
  45426. * @param scene The scene the lights belongs to
  45427. */
  45428. function PointLight(name, position, scene) {
  45429. var _this = _super.call(this, name, scene) || this;
  45430. _this._shadowAngle = Math.PI / 2;
  45431. _this.position = position;
  45432. return _this;
  45433. }
  45434. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  45435. /**
  45436. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45437. * This specifies what angle the shadow will use to be created.
  45438. *
  45439. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45440. */
  45441. get: function () {
  45442. return this._shadowAngle;
  45443. },
  45444. /**
  45445. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45446. * This specifies what angle the shadow will use to be created.
  45447. *
  45448. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45449. */
  45450. set: function (value) {
  45451. this._shadowAngle = value;
  45452. this.forceProjectionMatrixCompute();
  45453. },
  45454. enumerable: true,
  45455. configurable: true
  45456. });
  45457. Object.defineProperty(PointLight.prototype, "direction", {
  45458. /**
  45459. * Gets the direction if it has been set.
  45460. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45461. */
  45462. get: function () {
  45463. return this._direction;
  45464. },
  45465. /**
  45466. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45467. */
  45468. set: function (value) {
  45469. var previousNeedCube = this.needCube();
  45470. this._direction = value;
  45471. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  45472. this._shadowGenerator.recreateShadowMap();
  45473. }
  45474. },
  45475. enumerable: true,
  45476. configurable: true
  45477. });
  45478. /**
  45479. * Returns the string "PointLight"
  45480. * @returns the class name
  45481. */
  45482. PointLight.prototype.getClassName = function () {
  45483. return "PointLight";
  45484. };
  45485. /**
  45486. * Returns the integer 0.
  45487. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45488. */
  45489. PointLight.prototype.getTypeID = function () {
  45490. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  45491. };
  45492. /**
  45493. * Specifies wether or not the shadowmap should be a cube texture.
  45494. * @returns true if the shadowmap needs to be a cube texture.
  45495. */
  45496. PointLight.prototype.needCube = function () {
  45497. return !this.direction;
  45498. };
  45499. /**
  45500. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  45501. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45502. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45503. */
  45504. PointLight.prototype.getShadowDirection = function (faceIndex) {
  45505. if (this.direction) {
  45506. return _super.prototype.getShadowDirection.call(this, faceIndex);
  45507. }
  45508. else {
  45509. switch (faceIndex) {
  45510. case 0:
  45511. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  45512. case 1:
  45513. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  45514. case 2:
  45515. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  45516. case 3:
  45517. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  45518. case 4:
  45519. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  45520. case 5:
  45521. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  45522. }
  45523. }
  45524. return BABYLON.Vector3.Zero();
  45525. };
  45526. /**
  45527. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  45528. * - fov = PI / 2
  45529. * - aspect ratio : 1.0
  45530. * - z-near and far equal to the active camera minZ and maxZ.
  45531. * Returns the PointLight.
  45532. */
  45533. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45534. var activeCamera = this.getScene().activeCamera;
  45535. if (!activeCamera) {
  45536. return;
  45537. }
  45538. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45539. };
  45540. PointLight.prototype._buildUniformLayout = function () {
  45541. this._uniformBuffer.addUniform("vLightData", 4);
  45542. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45543. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45544. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45545. this._uniformBuffer.addUniform("depthValues", 2);
  45546. this._uniformBuffer.create();
  45547. };
  45548. /**
  45549. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  45550. * @param effect The effect to update
  45551. * @param lightIndex The index of the light in the effect to update
  45552. * @returns The point light
  45553. */
  45554. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  45555. if (this.computeTransformedInformation()) {
  45556. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  45557. return this;
  45558. }
  45559. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  45560. return this;
  45561. };
  45562. __decorate([
  45563. BABYLON.serialize()
  45564. ], PointLight.prototype, "shadowAngle", null);
  45565. return PointLight;
  45566. }(BABYLON.ShadowLight));
  45567. BABYLON.PointLight = PointLight;
  45568. })(BABYLON || (BABYLON = {}));
  45569. //# sourceMappingURL=babylon.pointLight.js.map
  45570. var BABYLON;
  45571. (function (BABYLON) {
  45572. /**
  45573. * A directional light is defined by a direction (what a surprise!).
  45574. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  45575. * 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.
  45576. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45577. */
  45578. var DirectionalLight = /** @class */ (function (_super) {
  45579. __extends(DirectionalLight, _super);
  45580. /**
  45581. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  45582. * The directional light is emitted from everywhere in the given direction.
  45583. * It can cast shawdows.
  45584. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45585. * @param name The friendly name of the light
  45586. * @param direction The direction of the light
  45587. * @param scene The scene the light belongs to
  45588. */
  45589. function DirectionalLight(name, direction, scene) {
  45590. var _this = _super.call(this, name, scene) || this;
  45591. _this._shadowFrustumSize = 0;
  45592. _this._shadowOrthoScale = 0.5;
  45593. /**
  45594. * Automatically compute the projection matrix to best fit (including all the casters)
  45595. * on each frame.
  45596. */
  45597. _this.autoUpdateExtends = true;
  45598. // Cache
  45599. _this._orthoLeft = Number.MAX_VALUE;
  45600. _this._orthoRight = Number.MIN_VALUE;
  45601. _this._orthoTop = Number.MIN_VALUE;
  45602. _this._orthoBottom = Number.MAX_VALUE;
  45603. _this.position = direction.scale(-1.0);
  45604. _this.direction = direction;
  45605. return _this;
  45606. }
  45607. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  45608. /**
  45609. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  45610. */
  45611. get: function () {
  45612. return this._shadowFrustumSize;
  45613. },
  45614. /**
  45615. * Specifies a fix frustum size for the shadow generation.
  45616. */
  45617. set: function (value) {
  45618. this._shadowFrustumSize = value;
  45619. this.forceProjectionMatrixCompute();
  45620. },
  45621. enumerable: true,
  45622. configurable: true
  45623. });
  45624. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  45625. /**
  45626. * Gets the shadow projection scale against the optimal computed one.
  45627. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45628. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45629. */
  45630. get: function () {
  45631. return this._shadowOrthoScale;
  45632. },
  45633. /**
  45634. * Sets the shadow projection scale against the optimal computed one.
  45635. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45636. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45637. */
  45638. set: function (value) {
  45639. this._shadowOrthoScale = value;
  45640. this.forceProjectionMatrixCompute();
  45641. },
  45642. enumerable: true,
  45643. configurable: true
  45644. });
  45645. /**
  45646. * Returns the string "DirectionalLight".
  45647. * @return The class name
  45648. */
  45649. DirectionalLight.prototype.getClassName = function () {
  45650. return "DirectionalLight";
  45651. };
  45652. /**
  45653. * Returns the integer 1.
  45654. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45655. */
  45656. DirectionalLight.prototype.getTypeID = function () {
  45657. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  45658. };
  45659. /**
  45660. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  45661. * Returns the DirectionalLight Shadow projection matrix.
  45662. */
  45663. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45664. if (this.shadowFrustumSize > 0) {
  45665. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  45666. }
  45667. else {
  45668. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45669. }
  45670. };
  45671. /**
  45672. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  45673. * Returns the DirectionalLight Shadow projection matrix.
  45674. */
  45675. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  45676. var activeCamera = this.getScene().activeCamera;
  45677. if (!activeCamera) {
  45678. return;
  45679. }
  45680. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  45681. };
  45682. /**
  45683. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  45684. * Returns the DirectionalLight Shadow projection matrix.
  45685. */
  45686. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45687. var activeCamera = this.getScene().activeCamera;
  45688. if (!activeCamera) {
  45689. return;
  45690. }
  45691. // Check extends
  45692. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  45693. var tempVector3 = BABYLON.Vector3.Zero();
  45694. this._orthoLeft = Number.MAX_VALUE;
  45695. this._orthoRight = Number.MIN_VALUE;
  45696. this._orthoTop = Number.MIN_VALUE;
  45697. this._orthoBottom = Number.MAX_VALUE;
  45698. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  45699. var mesh = renderList[meshIndex];
  45700. if (!mesh) {
  45701. continue;
  45702. }
  45703. var boundingInfo = mesh.getBoundingInfo();
  45704. var boundingBox = boundingInfo.boundingBox;
  45705. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  45706. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  45707. if (tempVector3.x < this._orthoLeft)
  45708. this._orthoLeft = tempVector3.x;
  45709. if (tempVector3.y < this._orthoBottom)
  45710. this._orthoBottom = tempVector3.y;
  45711. if (tempVector3.x > this._orthoRight)
  45712. this._orthoRight = tempVector3.x;
  45713. if (tempVector3.y > this._orthoTop)
  45714. this._orthoTop = tempVector3.y;
  45715. }
  45716. }
  45717. }
  45718. var xOffset = this._orthoRight - this._orthoLeft;
  45719. var yOffset = this._orthoTop - this._orthoBottom;
  45720. 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);
  45721. };
  45722. DirectionalLight.prototype._buildUniformLayout = function () {
  45723. this._uniformBuffer.addUniform("vLightData", 4);
  45724. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45725. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45726. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45727. this._uniformBuffer.addUniform("depthValues", 2);
  45728. this._uniformBuffer.create();
  45729. };
  45730. /**
  45731. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  45732. * @param effect The effect to update
  45733. * @param lightIndex The index of the light in the effect to update
  45734. * @returns The directional light
  45735. */
  45736. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  45737. if (this.computeTransformedInformation()) {
  45738. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  45739. return this;
  45740. }
  45741. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  45742. return this;
  45743. };
  45744. /**
  45745. * Gets the minZ used for shadow according to both the scene and the light.
  45746. *
  45747. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45748. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45749. * @param activeCamera The camera we are returning the min for
  45750. * @returns the depth min z
  45751. */
  45752. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  45753. return 1;
  45754. };
  45755. /**
  45756. * Gets the maxZ used for shadow according to both the scene and the light.
  45757. *
  45758. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45759. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45760. * @param activeCamera The camera we are returning the max for
  45761. * @returns the depth max z
  45762. */
  45763. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  45764. return 1;
  45765. };
  45766. __decorate([
  45767. BABYLON.serialize()
  45768. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  45769. __decorate([
  45770. BABYLON.serialize()
  45771. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  45772. __decorate([
  45773. BABYLON.serialize()
  45774. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  45775. return DirectionalLight;
  45776. }(BABYLON.ShadowLight));
  45777. BABYLON.DirectionalLight = DirectionalLight;
  45778. })(BABYLON || (BABYLON = {}));
  45779. //# sourceMappingURL=babylon.directionalLight.js.map
  45780. var BABYLON;
  45781. (function (BABYLON) {
  45782. /**
  45783. * A spot light is defined by a position, a direction, an angle, and an exponent.
  45784. * These values define a cone of light starting from the position, emitting toward the direction.
  45785. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  45786. * and the exponent defines the speed of the decay of the light with distance (reach).
  45787. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45788. */
  45789. var SpotLight = /** @class */ (function (_super) {
  45790. __extends(SpotLight, _super);
  45791. /**
  45792. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  45793. * It can cast shadows.
  45794. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45795. * @param name The light friendly name
  45796. * @param position The position of the spot light in the scene
  45797. * @param direction The direction of the light in the scene
  45798. * @param angle The cone angle of the light in Radians
  45799. * @param exponent The light decay speed with the distance from the emission spot
  45800. * @param scene The scene the lights belongs to
  45801. */
  45802. function SpotLight(name, position, direction, angle, exponent, scene) {
  45803. var _this = _super.call(this, name, scene) || this;
  45804. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  45805. _this._projectionTextureLightNear = 1e-6;
  45806. _this._projectionTextureLightFar = 1000.0;
  45807. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  45808. _this._projectionTextureViewLightDirty = true;
  45809. _this._projectionTextureProjectionLightDirty = true;
  45810. _this._projectionTextureDirty = true;
  45811. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  45812. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  45813. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  45814. _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);
  45815. _this.position = position;
  45816. _this.direction = direction;
  45817. _this.angle = angle;
  45818. _this.exponent = exponent;
  45819. return _this;
  45820. }
  45821. Object.defineProperty(SpotLight.prototype, "angle", {
  45822. /**
  45823. * Gets the cone angle of the spot light in Radians.
  45824. */
  45825. get: function () {
  45826. return this._angle;
  45827. },
  45828. /**
  45829. * Sets the cone angle of the spot light in Radians.
  45830. */
  45831. set: function (value) {
  45832. this._angle = value;
  45833. this._projectionTextureProjectionLightDirty = true;
  45834. this.forceProjectionMatrixCompute();
  45835. },
  45836. enumerable: true,
  45837. configurable: true
  45838. });
  45839. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  45840. /**
  45841. * Allows scaling the angle of the light for shadow generation only.
  45842. */
  45843. get: function () {
  45844. return this._shadowAngleScale;
  45845. },
  45846. /**
  45847. * Allows scaling the angle of the light for shadow generation only.
  45848. */
  45849. set: function (value) {
  45850. this._shadowAngleScale = value;
  45851. this.forceProjectionMatrixCompute();
  45852. },
  45853. enumerable: true,
  45854. configurable: true
  45855. });
  45856. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  45857. /**
  45858. * Allows reading the projecton texture
  45859. */
  45860. get: function () {
  45861. return this._projectionTextureMatrix;
  45862. },
  45863. enumerable: true,
  45864. configurable: true
  45865. });
  45866. ;
  45867. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  45868. /**
  45869. * Gets the near clip of the Spotlight for texture projection.
  45870. */
  45871. get: function () {
  45872. return this._projectionTextureLightNear;
  45873. },
  45874. /**
  45875. * Sets the near clip of the Spotlight for texture projection.
  45876. */
  45877. set: function (value) {
  45878. this._projectionTextureLightNear = value;
  45879. this._projectionTextureProjectionLightDirty = true;
  45880. },
  45881. enumerable: true,
  45882. configurable: true
  45883. });
  45884. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  45885. /**
  45886. * Gets the far clip of the Spotlight for texture projection.
  45887. */
  45888. get: function () {
  45889. return this._projectionTextureLightFar;
  45890. },
  45891. /**
  45892. * Sets the far clip of the Spotlight for texture projection.
  45893. */
  45894. set: function (value) {
  45895. this._projectionTextureLightFar = value;
  45896. this._projectionTextureProjectionLightDirty = true;
  45897. },
  45898. enumerable: true,
  45899. configurable: true
  45900. });
  45901. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  45902. /**
  45903. * Gets the Up vector of the Spotlight for texture projection.
  45904. */
  45905. get: function () {
  45906. return this._projectionTextureUpDirection;
  45907. },
  45908. /**
  45909. * Sets the Up vector of the Spotlight for texture projection.
  45910. */
  45911. set: function (value) {
  45912. this._projectionTextureUpDirection = value;
  45913. this._projectionTextureProjectionLightDirty = true;
  45914. },
  45915. enumerable: true,
  45916. configurable: true
  45917. });
  45918. ;
  45919. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  45920. /**
  45921. * Gets the projection texture of the light.
  45922. */
  45923. get: function () {
  45924. return this._projectionTexture;
  45925. },
  45926. /**
  45927. * Sets the projection texture of the light.
  45928. */
  45929. set: function (value) {
  45930. this._projectionTexture = value;
  45931. this._projectionTextureDirty = true;
  45932. },
  45933. enumerable: true,
  45934. configurable: true
  45935. });
  45936. /**
  45937. * Returns the string "SpotLight".
  45938. * @returns the class name
  45939. */
  45940. SpotLight.prototype.getClassName = function () {
  45941. return "SpotLight";
  45942. };
  45943. /**
  45944. * Returns the integer 2.
  45945. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45946. */
  45947. SpotLight.prototype.getTypeID = function () {
  45948. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  45949. };
  45950. /**
  45951. * Overrides the direction setter to recompute the projection texture view light Matrix.
  45952. */
  45953. SpotLight.prototype._setDirection = function (value) {
  45954. _super.prototype._setDirection.call(this, value);
  45955. this._projectionTextureViewLightDirty = true;
  45956. };
  45957. /**
  45958. * Overrides the position setter to recompute the projection texture view light Matrix.
  45959. */
  45960. SpotLight.prototype._setPosition = function (value) {
  45961. _super.prototype._setPosition.call(this, value);
  45962. this._projectionTextureViewLightDirty = true;
  45963. };
  45964. /**
  45965. * 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.
  45966. * Returns the SpotLight.
  45967. */
  45968. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45969. var activeCamera = this.getScene().activeCamera;
  45970. if (!activeCamera) {
  45971. return;
  45972. }
  45973. this._shadowAngleScale = this._shadowAngleScale || 1;
  45974. var angle = this._shadowAngleScale * this._angle;
  45975. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45976. };
  45977. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  45978. this._projectionTextureViewLightDirty = false;
  45979. this._projectionTextureDirty = true;
  45980. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  45981. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  45982. };
  45983. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  45984. this._projectionTextureProjectionLightDirty = false;
  45985. this._projectionTextureDirty = true;
  45986. var light_far = this.projectionTextureLightFar;
  45987. var light_near = this.projectionTextureLightNear;
  45988. var P = light_far / (light_far - light_near);
  45989. var Q = -P * light_near;
  45990. var S = 1.0 / Math.tan(this._angle / 2.0);
  45991. var A = 1.0;
  45992. 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);
  45993. };
  45994. /**
  45995. * Main function for light texture projection matrix computing.
  45996. */
  45997. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  45998. this._projectionTextureDirty = false;
  45999. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  46000. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  46001. };
  46002. SpotLight.prototype._buildUniformLayout = function () {
  46003. this._uniformBuffer.addUniform("vLightData", 4);
  46004. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46005. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46006. this._uniformBuffer.addUniform("vLightDirection", 3);
  46007. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46008. this._uniformBuffer.addUniform("depthValues", 2);
  46009. this._uniformBuffer.create();
  46010. };
  46011. /**
  46012. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  46013. * @param effect The effect to update
  46014. * @param lightIndex The index of the light in the effect to update
  46015. * @returns The spot light
  46016. */
  46017. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  46018. var normalizeDirection;
  46019. if (this.computeTransformedInformation()) {
  46020. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  46021. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  46022. }
  46023. else {
  46024. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  46025. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  46026. }
  46027. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  46028. if (this.projectionTexture && this.projectionTexture.isReady()) {
  46029. if (this._projectionTextureViewLightDirty) {
  46030. this._computeProjectionTextureViewLightMatrix();
  46031. }
  46032. if (this._projectionTextureProjectionLightDirty) {
  46033. this._computeProjectionTextureProjectionLightMatrix();
  46034. }
  46035. if (this._projectionTextureDirty) {
  46036. this._computeProjectionTextureMatrix();
  46037. }
  46038. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  46039. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  46040. }
  46041. return this;
  46042. };
  46043. /**
  46044. * Disposes the light and the associated resources.
  46045. */
  46046. SpotLight.prototype.dispose = function () {
  46047. _super.prototype.dispose.call(this);
  46048. if (this._projectionTexture) {
  46049. this._projectionTexture.dispose();
  46050. }
  46051. };
  46052. __decorate([
  46053. BABYLON.serialize()
  46054. ], SpotLight.prototype, "angle", null);
  46055. __decorate([
  46056. BABYLON.serialize()
  46057. ], SpotLight.prototype, "shadowAngleScale", null);
  46058. __decorate([
  46059. BABYLON.serialize()
  46060. ], SpotLight.prototype, "exponent", void 0);
  46061. __decorate([
  46062. BABYLON.serialize()
  46063. ], SpotLight.prototype, "projectionTextureLightNear", null);
  46064. __decorate([
  46065. BABYLON.serialize()
  46066. ], SpotLight.prototype, "projectionTextureLightFar", null);
  46067. __decorate([
  46068. BABYLON.serialize()
  46069. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46070. __decorate([
  46071. BABYLON.serializeAsTexture("projectedLightTexture")
  46072. ], SpotLight.prototype, "_projectionTexture", void 0);
  46073. return SpotLight;
  46074. }(BABYLON.ShadowLight));
  46075. BABYLON.SpotLight = SpotLight;
  46076. })(BABYLON || (BABYLON = {}));
  46077. //# sourceMappingURL=babylon.spotLight.js.map
  46078. var BABYLON;
  46079. (function (BABYLON) {
  46080. var AnimationRange = /** @class */ (function () {
  46081. function AnimationRange(name, from, to) {
  46082. this.name = name;
  46083. this.from = from;
  46084. this.to = to;
  46085. }
  46086. AnimationRange.prototype.clone = function () {
  46087. return new AnimationRange(this.name, this.from, this.to);
  46088. };
  46089. return AnimationRange;
  46090. }());
  46091. BABYLON.AnimationRange = AnimationRange;
  46092. /**
  46093. * Composed of a frame, and an action function
  46094. */
  46095. var AnimationEvent = /** @class */ (function () {
  46096. function AnimationEvent(frame, action, onlyOnce) {
  46097. this.frame = frame;
  46098. this.action = action;
  46099. this.onlyOnce = onlyOnce;
  46100. this.isDone = false;
  46101. }
  46102. return AnimationEvent;
  46103. }());
  46104. BABYLON.AnimationEvent = AnimationEvent;
  46105. var PathCursor = /** @class */ (function () {
  46106. function PathCursor(path) {
  46107. this.path = path;
  46108. this._onchange = new Array();
  46109. this.value = 0;
  46110. this.animations = new Array();
  46111. }
  46112. PathCursor.prototype.getPoint = function () {
  46113. var point = this.path.getPointAtLengthPosition(this.value);
  46114. return new BABYLON.Vector3(point.x, 0, point.y);
  46115. };
  46116. PathCursor.prototype.moveAhead = function (step) {
  46117. if (step === void 0) { step = 0.002; }
  46118. this.move(step);
  46119. return this;
  46120. };
  46121. PathCursor.prototype.moveBack = function (step) {
  46122. if (step === void 0) { step = 0.002; }
  46123. this.move(-step);
  46124. return this;
  46125. };
  46126. PathCursor.prototype.move = function (step) {
  46127. if (Math.abs(step) > 1) {
  46128. throw "step size should be less than 1.";
  46129. }
  46130. this.value += step;
  46131. this.ensureLimits();
  46132. this.raiseOnChange();
  46133. return this;
  46134. };
  46135. PathCursor.prototype.ensureLimits = function () {
  46136. while (this.value > 1) {
  46137. this.value -= 1;
  46138. }
  46139. while (this.value < 0) {
  46140. this.value += 1;
  46141. }
  46142. return this;
  46143. };
  46144. // used by animation engine
  46145. PathCursor.prototype.raiseOnChange = function () {
  46146. var _this = this;
  46147. this._onchange.forEach(function (f) { return f(_this); });
  46148. return this;
  46149. };
  46150. PathCursor.prototype.onchange = function (f) {
  46151. this._onchange.push(f);
  46152. return this;
  46153. };
  46154. return PathCursor;
  46155. }());
  46156. BABYLON.PathCursor = PathCursor;
  46157. var AnimationKeyInterpolation;
  46158. (function (AnimationKeyInterpolation) {
  46159. /**
  46160. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46161. */
  46162. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46163. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46164. var Animation = /** @class */ (function () {
  46165. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46166. this.name = name;
  46167. this.targetProperty = targetProperty;
  46168. this.framePerSecond = framePerSecond;
  46169. this.dataType = dataType;
  46170. this.loopMode = loopMode;
  46171. this.enableBlending = enableBlending;
  46172. this._runtimeAnimations = new Array();
  46173. // The set of event that will be linked to this animation
  46174. this._events = new Array();
  46175. this.blendingSpeed = 0.01;
  46176. this._ranges = {};
  46177. this.targetPropertyPath = targetProperty.split(".");
  46178. this.dataType = dataType;
  46179. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46180. }
  46181. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46182. var dataType = undefined;
  46183. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46184. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46185. }
  46186. else if (from instanceof BABYLON.Quaternion) {
  46187. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46188. }
  46189. else if (from instanceof BABYLON.Vector3) {
  46190. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46191. }
  46192. else if (from instanceof BABYLON.Vector2) {
  46193. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46194. }
  46195. else if (from instanceof BABYLON.Color3) {
  46196. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46197. }
  46198. else if (from instanceof BABYLON.Size) {
  46199. dataType = Animation.ANIMATIONTYPE_SIZE;
  46200. }
  46201. if (dataType == undefined) {
  46202. return null;
  46203. }
  46204. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  46205. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  46206. animation.setKeys(keys);
  46207. if (easingFunction !== undefined) {
  46208. animation.setEasingFunction(easingFunction);
  46209. }
  46210. return animation;
  46211. };
  46212. /**
  46213. * Sets up an animation.
  46214. * @param property the property to animate
  46215. * @param animationType the animation type to apply
  46216. * @param easingFunction the easing function used in the animation
  46217. * @returns The created animation
  46218. */
  46219. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  46220. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  46221. animation.setEasingFunction(easingFunction);
  46222. return animation;
  46223. };
  46224. /**
  46225. * Create and start an animation on a node
  46226. * @param {string} name defines the name of the global animation that will be run on all nodes
  46227. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46228. * @param {string} targetProperty defines property to animate
  46229. * @param {number} framePerSecond defines the number of frame per second yo use
  46230. * @param {number} totalFrame defines the number of frames in total
  46231. * @param {any} from defines the initial value
  46232. * @param {any} to defines the final value
  46233. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46234. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46235. * @param onAnimationEnd defines the callback to call when animation end
  46236. * @returns the animatable created for this animation
  46237. */
  46238. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46239. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46240. if (!animation) {
  46241. return null;
  46242. }
  46243. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46244. };
  46245. /**
  46246. * Create and start an animation on a node and its descendants
  46247. * @param {string} name defines the name of the global animation that will be run on all nodes
  46248. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46249. * @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.
  46250. * @param {string} targetProperty defines property to animate
  46251. * @param {number} framePerSecond defines the number of frame per second yo use
  46252. * @param {number} totalFrame defines the number of frames in total
  46253. * @param {any} from defines the initial value
  46254. * @param {any} to defines the final value
  46255. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46256. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46257. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  46258. * @returns the list of animatables created for all nodes
  46259. * @example https://www.babylonjs-playground.com/#MH0VLI
  46260. */
  46261. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46262. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46263. if (!animation) {
  46264. return null;
  46265. }
  46266. var scene = node.getScene();
  46267. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46268. };
  46269. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46270. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46271. if (!animation) {
  46272. return null;
  46273. }
  46274. node.animations.push(animation);
  46275. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46276. };
  46277. /**
  46278. * Transition property of the Camera to the target Value.
  46279. * @param property The property to transition
  46280. * @param targetValue The target Value of the property
  46281. * @param host The object where the property to animate belongs
  46282. * @param scene Scene used to run the animation
  46283. * @param frameRate Framerate (in frame/s) to use
  46284. * @param transition The transition type we want to use
  46285. * @param duration The duration of the animation, in milliseconds
  46286. * @param onAnimationEnd Call back trigger at the end of the animation.
  46287. */
  46288. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  46289. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  46290. if (duration <= 0) {
  46291. host[property] = targetValue;
  46292. if (onAnimationEnd) {
  46293. onAnimationEnd();
  46294. }
  46295. return null;
  46296. }
  46297. var endFrame = frameRate * (duration / 1000);
  46298. transition.setKeys([{
  46299. frame: 0,
  46300. value: host[property].clone ? host[property].clone() : host[property]
  46301. },
  46302. {
  46303. frame: endFrame,
  46304. value: targetValue
  46305. }]);
  46306. if (!host.animations) {
  46307. host.animations = [];
  46308. }
  46309. host.animations.push(transition);
  46310. var animation = scene.beginAnimation(host, 0, endFrame, false);
  46311. animation.onAnimationEnd = onAnimationEnd;
  46312. return animation;
  46313. };
  46314. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  46315. /**
  46316. * Return the array of runtime animations currently using this animation
  46317. */
  46318. get: function () {
  46319. return this._runtimeAnimations;
  46320. },
  46321. enumerable: true,
  46322. configurable: true
  46323. });
  46324. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  46325. get: function () {
  46326. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  46327. var runtimeAnimation = _a[_i];
  46328. if (!runtimeAnimation.isStopped) {
  46329. return true;
  46330. }
  46331. }
  46332. return false;
  46333. },
  46334. enumerable: true,
  46335. configurable: true
  46336. });
  46337. // Methods
  46338. /**
  46339. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  46340. */
  46341. Animation.prototype.toString = function (fullDetails) {
  46342. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  46343. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  46344. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  46345. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  46346. if (fullDetails) {
  46347. ret += ", Ranges: {";
  46348. var first = true;
  46349. for (var name in this._ranges) {
  46350. if (first) {
  46351. ret += ", ";
  46352. first = false;
  46353. }
  46354. ret += name;
  46355. }
  46356. ret += "}";
  46357. }
  46358. return ret;
  46359. };
  46360. /**
  46361. * Add an event to this animation.
  46362. */
  46363. Animation.prototype.addEvent = function (event) {
  46364. this._events.push(event);
  46365. };
  46366. /**
  46367. * Remove all events found at the given frame
  46368. * @param frame
  46369. */
  46370. Animation.prototype.removeEvents = function (frame) {
  46371. for (var index = 0; index < this._events.length; index++) {
  46372. if (this._events[index].frame === frame) {
  46373. this._events.splice(index, 1);
  46374. index--;
  46375. }
  46376. }
  46377. };
  46378. Animation.prototype.getEvents = function () {
  46379. return this._events;
  46380. };
  46381. Animation.prototype.createRange = function (name, from, to) {
  46382. // check name not already in use; could happen for bones after serialized
  46383. if (!this._ranges[name]) {
  46384. this._ranges[name] = new AnimationRange(name, from, to);
  46385. }
  46386. };
  46387. Animation.prototype.deleteRange = function (name, deleteFrames) {
  46388. if (deleteFrames === void 0) { deleteFrames = true; }
  46389. var range = this._ranges[name];
  46390. if (!range) {
  46391. return;
  46392. }
  46393. if (deleteFrames) {
  46394. var from = range.from;
  46395. var to = range.to;
  46396. // this loop MUST go high to low for multiple splices to work
  46397. for (var key = this._keys.length - 1; key >= 0; key--) {
  46398. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  46399. this._keys.splice(key, 1);
  46400. }
  46401. }
  46402. }
  46403. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  46404. };
  46405. Animation.prototype.getRange = function (name) {
  46406. return this._ranges[name];
  46407. };
  46408. Animation.prototype.getKeys = function () {
  46409. return this._keys;
  46410. };
  46411. Animation.prototype.getHighestFrame = function () {
  46412. var ret = 0;
  46413. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  46414. if (ret < this._keys[key].frame) {
  46415. ret = this._keys[key].frame;
  46416. }
  46417. }
  46418. return ret;
  46419. };
  46420. Animation.prototype.getEasingFunction = function () {
  46421. return this._easingFunction;
  46422. };
  46423. Animation.prototype.setEasingFunction = function (easingFunction) {
  46424. this._easingFunction = easingFunction;
  46425. };
  46426. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  46427. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  46428. };
  46429. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46430. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46431. };
  46432. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  46433. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  46434. };
  46435. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46436. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  46437. };
  46438. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  46439. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  46440. };
  46441. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46442. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46443. };
  46444. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  46445. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  46446. };
  46447. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46448. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46449. };
  46450. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  46451. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  46452. };
  46453. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  46454. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  46455. };
  46456. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  46457. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  46458. };
  46459. Animation.prototype.clone = function () {
  46460. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  46461. clone.enableBlending = this.enableBlending;
  46462. clone.blendingSpeed = this.blendingSpeed;
  46463. if (this._keys) {
  46464. clone.setKeys(this._keys);
  46465. }
  46466. if (this._ranges) {
  46467. clone._ranges = {};
  46468. for (var name in this._ranges) {
  46469. var range = this._ranges[name];
  46470. if (!range) {
  46471. continue;
  46472. }
  46473. clone._ranges[name] = range.clone();
  46474. }
  46475. }
  46476. return clone;
  46477. };
  46478. Animation.prototype.setKeys = function (values) {
  46479. this._keys = values.slice(0);
  46480. };
  46481. Animation.prototype.serialize = function () {
  46482. var serializationObject = {};
  46483. serializationObject.name = this.name;
  46484. serializationObject.property = this.targetProperty;
  46485. serializationObject.framePerSecond = this.framePerSecond;
  46486. serializationObject.dataType = this.dataType;
  46487. serializationObject.loopBehavior = this.loopMode;
  46488. serializationObject.enableBlending = this.enableBlending;
  46489. serializationObject.blendingSpeed = this.blendingSpeed;
  46490. var dataType = this.dataType;
  46491. serializationObject.keys = [];
  46492. var keys = this.getKeys();
  46493. for (var index = 0; index < keys.length; index++) {
  46494. var animationKey = keys[index];
  46495. var key = {};
  46496. key.frame = animationKey.frame;
  46497. switch (dataType) {
  46498. case Animation.ANIMATIONTYPE_FLOAT:
  46499. key.values = [animationKey.value];
  46500. break;
  46501. case Animation.ANIMATIONTYPE_QUATERNION:
  46502. case Animation.ANIMATIONTYPE_MATRIX:
  46503. case Animation.ANIMATIONTYPE_VECTOR3:
  46504. case Animation.ANIMATIONTYPE_COLOR3:
  46505. key.values = animationKey.value.asArray();
  46506. break;
  46507. }
  46508. serializationObject.keys.push(key);
  46509. }
  46510. serializationObject.ranges = [];
  46511. for (var name in this._ranges) {
  46512. var source = this._ranges[name];
  46513. if (!source) {
  46514. continue;
  46515. }
  46516. var range = {};
  46517. range.name = name;
  46518. range.from = source.from;
  46519. range.to = source.to;
  46520. serializationObject.ranges.push(range);
  46521. }
  46522. return serializationObject;
  46523. };
  46524. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  46525. get: function () {
  46526. return Animation._ANIMATIONTYPE_FLOAT;
  46527. },
  46528. enumerable: true,
  46529. configurable: true
  46530. });
  46531. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  46532. get: function () {
  46533. return Animation._ANIMATIONTYPE_VECTOR3;
  46534. },
  46535. enumerable: true,
  46536. configurable: true
  46537. });
  46538. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  46539. get: function () {
  46540. return Animation._ANIMATIONTYPE_VECTOR2;
  46541. },
  46542. enumerable: true,
  46543. configurable: true
  46544. });
  46545. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  46546. get: function () {
  46547. return Animation._ANIMATIONTYPE_SIZE;
  46548. },
  46549. enumerable: true,
  46550. configurable: true
  46551. });
  46552. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  46553. get: function () {
  46554. return Animation._ANIMATIONTYPE_QUATERNION;
  46555. },
  46556. enumerable: true,
  46557. configurable: true
  46558. });
  46559. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  46560. get: function () {
  46561. return Animation._ANIMATIONTYPE_MATRIX;
  46562. },
  46563. enumerable: true,
  46564. configurable: true
  46565. });
  46566. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  46567. get: function () {
  46568. return Animation._ANIMATIONTYPE_COLOR3;
  46569. },
  46570. enumerable: true,
  46571. configurable: true
  46572. });
  46573. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  46574. get: function () {
  46575. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  46576. },
  46577. enumerable: true,
  46578. configurable: true
  46579. });
  46580. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  46581. get: function () {
  46582. return Animation._ANIMATIONLOOPMODE_CYCLE;
  46583. },
  46584. enumerable: true,
  46585. configurable: true
  46586. });
  46587. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  46588. get: function () {
  46589. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  46590. },
  46591. enumerable: true,
  46592. configurable: true
  46593. });
  46594. Animation.Parse = function (parsedAnimation) {
  46595. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  46596. var dataType = parsedAnimation.dataType;
  46597. var keys = [];
  46598. var data;
  46599. var index;
  46600. if (parsedAnimation.enableBlending) {
  46601. animation.enableBlending = parsedAnimation.enableBlending;
  46602. }
  46603. if (parsedAnimation.blendingSpeed) {
  46604. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  46605. }
  46606. for (index = 0; index < parsedAnimation.keys.length; index++) {
  46607. var key = parsedAnimation.keys[index];
  46608. var inTangent;
  46609. var outTangent;
  46610. switch (dataType) {
  46611. case Animation.ANIMATIONTYPE_FLOAT:
  46612. data = key.values[0];
  46613. if (key.values.length >= 1) {
  46614. inTangent = key.values[1];
  46615. }
  46616. if (key.values.length >= 2) {
  46617. outTangent = key.values[2];
  46618. }
  46619. break;
  46620. case Animation.ANIMATIONTYPE_QUATERNION:
  46621. data = BABYLON.Quaternion.FromArray(key.values);
  46622. if (key.values.length >= 8) {
  46623. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  46624. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  46625. inTangent = _inTangent;
  46626. }
  46627. }
  46628. if (key.values.length >= 12) {
  46629. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  46630. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  46631. outTangent = _outTangent;
  46632. }
  46633. }
  46634. break;
  46635. case Animation.ANIMATIONTYPE_MATRIX:
  46636. data = BABYLON.Matrix.FromArray(key.values);
  46637. break;
  46638. case Animation.ANIMATIONTYPE_COLOR3:
  46639. data = BABYLON.Color3.FromArray(key.values);
  46640. break;
  46641. case Animation.ANIMATIONTYPE_VECTOR3:
  46642. default:
  46643. data = BABYLON.Vector3.FromArray(key.values);
  46644. break;
  46645. }
  46646. var keyData = {};
  46647. keyData.frame = key.frame;
  46648. keyData.value = data;
  46649. if (inTangent != undefined) {
  46650. keyData.inTangent = inTangent;
  46651. }
  46652. if (outTangent != undefined) {
  46653. keyData.outTangent = outTangent;
  46654. }
  46655. keys.push(keyData);
  46656. }
  46657. animation.setKeys(keys);
  46658. if (parsedAnimation.ranges) {
  46659. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  46660. data = parsedAnimation.ranges[index];
  46661. animation.createRange(data.name, data.from, data.to);
  46662. }
  46663. }
  46664. return animation;
  46665. };
  46666. Animation.AppendSerializedAnimations = function (source, destination) {
  46667. if (source.animations) {
  46668. destination.animations = [];
  46669. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  46670. var animation = source.animations[animationIndex];
  46671. destination.animations.push(animation.serialize());
  46672. }
  46673. }
  46674. };
  46675. Animation.AllowMatricesInterpolation = false;
  46676. // Statics
  46677. Animation._ANIMATIONTYPE_FLOAT = 0;
  46678. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  46679. Animation._ANIMATIONTYPE_QUATERNION = 2;
  46680. Animation._ANIMATIONTYPE_MATRIX = 3;
  46681. Animation._ANIMATIONTYPE_COLOR3 = 4;
  46682. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  46683. Animation._ANIMATIONTYPE_SIZE = 6;
  46684. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  46685. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  46686. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  46687. return Animation;
  46688. }());
  46689. BABYLON.Animation = Animation;
  46690. })(BABYLON || (BABYLON = {}));
  46691. //# sourceMappingURL=babylon.animation.js.map
  46692. var BABYLON;
  46693. (function (BABYLON) {
  46694. /**
  46695. * This class defines the direct association between an animation and a target
  46696. */
  46697. var TargetedAnimation = /** @class */ (function () {
  46698. function TargetedAnimation() {
  46699. }
  46700. return TargetedAnimation;
  46701. }());
  46702. BABYLON.TargetedAnimation = TargetedAnimation;
  46703. /**
  46704. * Use this class to create coordinated animations on multiple targets
  46705. */
  46706. var AnimationGroup = /** @class */ (function () {
  46707. function AnimationGroup(name, scene) {
  46708. if (scene === void 0) { scene = null; }
  46709. this.name = name;
  46710. this._targetedAnimations = new Array();
  46711. this._animatables = new Array();
  46712. this._from = Number.MAX_VALUE;
  46713. this._to = -Number.MAX_VALUE;
  46714. this._speedRatio = 1;
  46715. this.onAnimationEndObservable = new BABYLON.Observable();
  46716. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46717. this._scene.animationGroups.push(this);
  46718. }
  46719. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  46720. /**
  46721. * Define if the animations are started
  46722. */
  46723. get: function () {
  46724. return this._isStarted;
  46725. },
  46726. enumerable: true,
  46727. configurable: true
  46728. });
  46729. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  46730. /**
  46731. * Gets or sets the speed ratio to use for all animations
  46732. */
  46733. get: function () {
  46734. return this._speedRatio;
  46735. },
  46736. /**
  46737. * Gets or sets the speed ratio to use for all animations
  46738. */
  46739. set: function (value) {
  46740. if (this._speedRatio === value) {
  46741. return;
  46742. }
  46743. this._speedRatio = value;
  46744. for (var index = 0; index < this._animatables.length; index++) {
  46745. var animatable = this._animatables[index];
  46746. animatable.speedRatio = this._speedRatio;
  46747. }
  46748. },
  46749. enumerable: true,
  46750. configurable: true
  46751. });
  46752. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  46753. /**
  46754. * Gets the targeted animations for this animation group
  46755. */
  46756. get: function () {
  46757. return this._targetedAnimations;
  46758. },
  46759. enumerable: true,
  46760. configurable: true
  46761. });
  46762. /**
  46763. * Add an animation (with its target) in the group
  46764. * @param animation defines the animation we want to add
  46765. * @param target defines the target of the animation
  46766. * @returns the {BABYLON.TargetedAnimation} object
  46767. */
  46768. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  46769. var targetedAnimation = {
  46770. animation: animation,
  46771. target: target
  46772. };
  46773. var keys = animation.getKeys();
  46774. if (this._from > keys[0].frame) {
  46775. this._from = keys[0].frame;
  46776. }
  46777. if (this._to < keys[keys.length - 1].frame) {
  46778. this._to = keys[keys.length - 1].frame;
  46779. }
  46780. this._targetedAnimations.push(targetedAnimation);
  46781. return targetedAnimation;
  46782. };
  46783. /**
  46784. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  46785. * It can add constant keys at begin or end
  46786. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  46787. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  46788. */
  46789. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  46790. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  46791. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  46792. beginFrame = Math.max(beginFrame, this._from);
  46793. endFrame = Math.min(endFrame, this._to);
  46794. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46795. var targetedAnimation = this._targetedAnimations[index];
  46796. var keys = targetedAnimation.animation.getKeys();
  46797. var startKey = keys[0];
  46798. var endKey = keys[keys.length - 1];
  46799. if (startKey.frame > beginFrame) {
  46800. var newKey = {
  46801. frame: beginFrame,
  46802. value: startKey.value,
  46803. inTangent: startKey.inTangent,
  46804. outTangent: startKey.outTangent,
  46805. interpolation: startKey.interpolation
  46806. };
  46807. keys.splice(0, 0, newKey);
  46808. }
  46809. if (endKey.frame < endFrame) {
  46810. var newKey = {
  46811. frame: endFrame,
  46812. value: endKey.value,
  46813. inTangent: endKey.outTangent,
  46814. outTangent: endKey.outTangent,
  46815. interpolation: endKey.interpolation
  46816. };
  46817. keys.push(newKey);
  46818. }
  46819. }
  46820. return this;
  46821. };
  46822. /**
  46823. * Start all animations on given targets
  46824. * @param loop defines if animations must loop
  46825. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  46826. */
  46827. AnimationGroup.prototype.start = function (loop, speedRatio) {
  46828. var _this = this;
  46829. if (loop === void 0) { loop = false; }
  46830. if (speedRatio === void 0) { speedRatio = 1; }
  46831. if (this._isStarted || this._targetedAnimations.length === 0) {
  46832. return this;
  46833. }
  46834. var _loop_1 = function () {
  46835. var targetedAnimation = this_1._targetedAnimations[index];
  46836. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  46837. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  46838. }));
  46839. };
  46840. var this_1 = this;
  46841. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46842. _loop_1();
  46843. }
  46844. this._speedRatio = speedRatio;
  46845. this._isStarted = true;
  46846. return this;
  46847. };
  46848. /**
  46849. * Pause all animations
  46850. */
  46851. AnimationGroup.prototype.pause = function () {
  46852. if (!this._isStarted) {
  46853. return this;
  46854. }
  46855. for (var index = 0; index < this._animatables.length; index++) {
  46856. var animatable = this._animatables[index];
  46857. animatable.pause();
  46858. }
  46859. return this;
  46860. };
  46861. /**
  46862. * Play all animations to initial state
  46863. * This function will start() the animations if they were not started or will restart() them if they were paused
  46864. * @param loop defines if animations must loop
  46865. */
  46866. AnimationGroup.prototype.play = function (loop) {
  46867. if (this.isStarted) {
  46868. if (loop !== undefined) {
  46869. for (var index = 0; index < this._animatables.length; index++) {
  46870. var animatable = this._animatables[index];
  46871. animatable.loopAnimation = loop;
  46872. }
  46873. }
  46874. this.restart();
  46875. }
  46876. else {
  46877. this.start(loop, this._speedRatio);
  46878. }
  46879. return this;
  46880. };
  46881. /**
  46882. * Reset all animations to initial state
  46883. */
  46884. AnimationGroup.prototype.reset = function () {
  46885. if (!this._isStarted) {
  46886. return this;
  46887. }
  46888. for (var index = 0; index < this._animatables.length; index++) {
  46889. var animatable = this._animatables[index];
  46890. animatable.reset();
  46891. }
  46892. return this;
  46893. };
  46894. /**
  46895. * Restart animations from key 0
  46896. */
  46897. AnimationGroup.prototype.restart = function () {
  46898. if (!this._isStarted) {
  46899. return this;
  46900. }
  46901. for (var index = 0; index < this._animatables.length; index++) {
  46902. var animatable = this._animatables[index];
  46903. animatable.restart();
  46904. }
  46905. return this;
  46906. };
  46907. /**
  46908. * Stop all animations
  46909. */
  46910. AnimationGroup.prototype.stop = function () {
  46911. if (!this._isStarted) {
  46912. return this;
  46913. }
  46914. for (var index = 0; index < this._animatables.length; index++) {
  46915. var animatable = this._animatables[index];
  46916. animatable.stop();
  46917. }
  46918. this._isStarted = false;
  46919. return this;
  46920. };
  46921. /**
  46922. * Dispose all associated resources
  46923. */
  46924. AnimationGroup.prototype.dispose = function () {
  46925. this._targetedAnimations = [];
  46926. this._animatables = [];
  46927. var index = this._scene.animationGroups.indexOf(this);
  46928. if (index > -1) {
  46929. this._scene.animationGroups.splice(index, 1);
  46930. }
  46931. };
  46932. return AnimationGroup;
  46933. }());
  46934. BABYLON.AnimationGroup = AnimationGroup;
  46935. })(BABYLON || (BABYLON = {}));
  46936. //# sourceMappingURL=babylon.animationGroup.js.map
  46937. var BABYLON;
  46938. (function (BABYLON) {
  46939. var RuntimeAnimation = /** @class */ (function () {
  46940. function RuntimeAnimation(target, animation) {
  46941. this._offsetsCache = {};
  46942. this._highLimitsCache = {};
  46943. this._stopped = false;
  46944. this._blendingFactor = 0;
  46945. this._ratioOffset = 0;
  46946. this._animation = animation;
  46947. this._target = target;
  46948. animation._runtimeAnimations.push(this);
  46949. }
  46950. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  46951. get: function () {
  46952. return this._animation;
  46953. },
  46954. enumerable: true,
  46955. configurable: true
  46956. });
  46957. RuntimeAnimation.prototype.reset = function () {
  46958. this._offsetsCache = {};
  46959. this._highLimitsCache = {};
  46960. this.currentFrame = 0;
  46961. this._blendingFactor = 0;
  46962. this._originalBlendValue = null;
  46963. };
  46964. RuntimeAnimation.prototype.isStopped = function () {
  46965. return this._stopped;
  46966. };
  46967. RuntimeAnimation.prototype.dispose = function () {
  46968. var index = this._animation.runtimeAnimations.indexOf(this);
  46969. if (index > -1) {
  46970. this._animation.runtimeAnimations.splice(index, 1);
  46971. }
  46972. };
  46973. RuntimeAnimation.prototype._getKeyValue = function (value) {
  46974. if (typeof value === "function") {
  46975. return value();
  46976. }
  46977. return value;
  46978. };
  46979. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  46980. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  46981. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  46982. }
  46983. this.currentFrame = currentFrame;
  46984. var keys = this._animation.getKeys();
  46985. // Try to get a hash to find the right key
  46986. 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));
  46987. if (keys[startKeyIndex].frame >= currentFrame) {
  46988. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  46989. startKeyIndex--;
  46990. }
  46991. }
  46992. for (var key = startKeyIndex; key < keys.length; key++) {
  46993. var endKey = keys[key + 1];
  46994. if (endKey.frame >= currentFrame) {
  46995. var startKey = keys[key];
  46996. var startValue = this._getKeyValue(startKey.value);
  46997. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  46998. return startValue;
  46999. }
  47000. var endValue = this._getKeyValue(endKey.value);
  47001. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  47002. var frameDelta = endKey.frame - startKey.frame;
  47003. // gradient : percent of currentFrame between the frame inf and the frame sup
  47004. var gradient = (currentFrame - startKey.frame) / frameDelta;
  47005. // check for easingFunction and correction of gradient
  47006. var easingFunction = this._animation.getEasingFunction();
  47007. if (easingFunction != null) {
  47008. gradient = easingFunction.ease(gradient);
  47009. }
  47010. switch (this._animation.dataType) {
  47011. // Float
  47012. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47013. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  47014. switch (loopMode) {
  47015. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47016. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47017. return floatValue;
  47018. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47019. return offsetValue * repeatCount + floatValue;
  47020. }
  47021. break;
  47022. // Quaternion
  47023. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47024. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  47025. switch (loopMode) {
  47026. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47027. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47028. return quatValue;
  47029. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47030. return quatValue.add(offsetValue.scale(repeatCount));
  47031. }
  47032. return quatValue;
  47033. // Vector3
  47034. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47035. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  47036. switch (loopMode) {
  47037. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47038. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47039. return vec3Value;
  47040. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47041. return vec3Value.add(offsetValue.scale(repeatCount));
  47042. }
  47043. // Vector2
  47044. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47045. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  47046. switch (loopMode) {
  47047. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47048. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47049. return vec2Value;
  47050. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47051. return vec2Value.add(offsetValue.scale(repeatCount));
  47052. }
  47053. // Size
  47054. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47055. switch (loopMode) {
  47056. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47057. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47058. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  47059. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47060. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47061. }
  47062. // Color3
  47063. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47064. switch (loopMode) {
  47065. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47066. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47067. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  47068. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47069. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47070. }
  47071. // Matrix
  47072. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47073. switch (loopMode) {
  47074. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47075. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47076. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47077. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47078. }
  47079. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47080. return startValue;
  47081. }
  47082. default:
  47083. break;
  47084. }
  47085. break;
  47086. }
  47087. }
  47088. return this._getKeyValue(keys[keys.length - 1].value);
  47089. };
  47090. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  47091. if (blend === void 0) { blend = false; }
  47092. // Set value
  47093. var path;
  47094. var destination;
  47095. var targetPropertyPath = this._animation.targetPropertyPath;
  47096. if (targetPropertyPath.length > 1) {
  47097. var property = this._target[targetPropertyPath[0]];
  47098. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  47099. property = property[targetPropertyPath[index]];
  47100. }
  47101. path = targetPropertyPath[targetPropertyPath.length - 1];
  47102. destination = property;
  47103. }
  47104. else {
  47105. path = targetPropertyPath[0];
  47106. destination = this._target;
  47107. }
  47108. // Blending
  47109. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  47110. if (!this._originalBlendValue) {
  47111. if (destination[path].clone) {
  47112. this._originalBlendValue = destination[path].clone();
  47113. }
  47114. else {
  47115. this._originalBlendValue = destination[path];
  47116. }
  47117. }
  47118. if (this._originalBlendValue.prototype) {
  47119. if (this._originalBlendValue.prototype.Lerp) {
  47120. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  47121. }
  47122. else {
  47123. destination[path] = currentValue;
  47124. }
  47125. }
  47126. else if (this._originalBlendValue.m) {
  47127. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  47128. }
  47129. else {
  47130. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  47131. }
  47132. this._blendingFactor += this._animation.blendingSpeed;
  47133. }
  47134. else {
  47135. destination[path] = currentValue;
  47136. }
  47137. if (this._target.markAsDirty) {
  47138. this._target.markAsDirty(this._animation.targetProperty);
  47139. }
  47140. };
  47141. RuntimeAnimation.prototype.goToFrame = function (frame) {
  47142. var keys = this._animation.getKeys();
  47143. if (frame < keys[0].frame) {
  47144. frame = keys[0].frame;
  47145. }
  47146. else if (frame > keys[keys.length - 1].frame) {
  47147. frame = keys[keys.length - 1].frame;
  47148. }
  47149. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  47150. this.setValue(currentValue);
  47151. };
  47152. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  47153. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  47154. this._ratioOffset = this._previousRatio - newRatio;
  47155. };
  47156. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  47157. if (blend === void 0) { blend = false; }
  47158. var targetPropertyPath = this._animation.targetPropertyPath;
  47159. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  47160. this._stopped = true;
  47161. return false;
  47162. }
  47163. var returnValue = true;
  47164. var keys = this._animation.getKeys();
  47165. // Adding a start key at frame 0 if missing
  47166. if (keys[0].frame !== 0) {
  47167. var newKey = { frame: 0, value: keys[0].value };
  47168. keys.splice(0, 0, newKey);
  47169. }
  47170. // Check limits
  47171. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  47172. from = keys[0].frame;
  47173. }
  47174. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  47175. to = keys[keys.length - 1].frame;
  47176. }
  47177. //to and from cannot be the same key
  47178. if (from === to) {
  47179. if (from > keys[0].frame) {
  47180. from--;
  47181. }
  47182. else if (to < keys[keys.length - 1].frame) {
  47183. to++;
  47184. }
  47185. }
  47186. // Compute ratio
  47187. var range = to - from;
  47188. var offsetValue;
  47189. // ratio represents the frame delta between from and to
  47190. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  47191. var highLimitValue = 0;
  47192. this._previousDelay = delay;
  47193. this._previousRatio = ratio;
  47194. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  47195. returnValue = false;
  47196. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  47197. }
  47198. else {
  47199. // Get max value if required
  47200. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  47201. var keyOffset = to.toString() + from.toString();
  47202. if (!this._offsetsCache[keyOffset]) {
  47203. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47204. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47205. switch (this._animation.dataType) {
  47206. // Float
  47207. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47208. this._offsetsCache[keyOffset] = toValue - fromValue;
  47209. break;
  47210. // Quaternion
  47211. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47212. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47213. break;
  47214. // Vector3
  47215. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47216. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47217. // Vector2
  47218. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47219. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47220. // Size
  47221. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47222. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47223. // Color3
  47224. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47225. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47226. default:
  47227. break;
  47228. }
  47229. this._highLimitsCache[keyOffset] = toValue;
  47230. }
  47231. highLimitValue = this._highLimitsCache[keyOffset];
  47232. offsetValue = this._offsetsCache[keyOffset];
  47233. }
  47234. }
  47235. if (offsetValue === undefined) {
  47236. switch (this._animation.dataType) {
  47237. // Float
  47238. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47239. offsetValue = 0;
  47240. break;
  47241. // Quaternion
  47242. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47243. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  47244. break;
  47245. // Vector3
  47246. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47247. offsetValue = BABYLON.Vector3.Zero();
  47248. break;
  47249. // Vector2
  47250. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47251. offsetValue = BABYLON.Vector2.Zero();
  47252. break;
  47253. // Size
  47254. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47255. offsetValue = BABYLON.Size.Zero();
  47256. break;
  47257. // Color3
  47258. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47259. offsetValue = BABYLON.Color3.Black();
  47260. }
  47261. }
  47262. // Compute value
  47263. var repeatCount = (ratio / range) >> 0;
  47264. var currentFrame = returnValue ? from + ratio % range : to;
  47265. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  47266. // Set value
  47267. this.setValue(currentValue);
  47268. // Check events
  47269. var events = this._animation.getEvents();
  47270. for (var index = 0; index < events.length; index++) {
  47271. // Make sure current frame has passed event frame and that event frame is within the current range
  47272. // Also, handle both forward and reverse animations
  47273. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  47274. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  47275. var event = events[index];
  47276. if (!event.isDone) {
  47277. // If event should be done only once, remove it.
  47278. if (event.onlyOnce) {
  47279. events.splice(index, 1);
  47280. index--;
  47281. }
  47282. event.isDone = true;
  47283. event.action();
  47284. } // Don't do anything if the event has already be done.
  47285. }
  47286. else if (events[index].isDone && !events[index].onlyOnce) {
  47287. // reset event, the animation is looping
  47288. events[index].isDone = false;
  47289. }
  47290. }
  47291. if (!returnValue) {
  47292. this._stopped = true;
  47293. }
  47294. return returnValue;
  47295. };
  47296. return RuntimeAnimation;
  47297. }());
  47298. BABYLON.RuntimeAnimation = RuntimeAnimation;
  47299. })(BABYLON || (BABYLON = {}));
  47300. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  47301. var BABYLON;
  47302. (function (BABYLON) {
  47303. var Animatable = /** @class */ (function () {
  47304. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  47305. if (fromFrame === void 0) { fromFrame = 0; }
  47306. if (toFrame === void 0) { toFrame = 100; }
  47307. if (loopAnimation === void 0) { loopAnimation = false; }
  47308. if (speedRatio === void 0) { speedRatio = 1.0; }
  47309. this.target = target;
  47310. this.fromFrame = fromFrame;
  47311. this.toFrame = toFrame;
  47312. this.loopAnimation = loopAnimation;
  47313. this.onAnimationEnd = onAnimationEnd;
  47314. this._localDelayOffset = null;
  47315. this._pausedDelay = null;
  47316. this._runtimeAnimations = new Array();
  47317. this._paused = false;
  47318. this._speedRatio = 1;
  47319. this.animationStarted = false;
  47320. if (animations) {
  47321. this.appendAnimations(target, animations);
  47322. }
  47323. this._speedRatio = speedRatio;
  47324. this._scene = scene;
  47325. scene._activeAnimatables.push(this);
  47326. }
  47327. Object.defineProperty(Animatable.prototype, "speedRatio", {
  47328. get: function () {
  47329. return this._speedRatio;
  47330. },
  47331. set: function (value) {
  47332. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  47333. var animation = this._runtimeAnimations[index];
  47334. animation._prepareForSpeedRatioChange(value);
  47335. }
  47336. this._speedRatio = value;
  47337. },
  47338. enumerable: true,
  47339. configurable: true
  47340. });
  47341. // Methods
  47342. Animatable.prototype.getAnimations = function () {
  47343. return this._runtimeAnimations;
  47344. };
  47345. Animatable.prototype.appendAnimations = function (target, animations) {
  47346. for (var index = 0; index < animations.length; index++) {
  47347. var animation = animations[index];
  47348. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  47349. }
  47350. };
  47351. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  47352. var runtimeAnimations = this._runtimeAnimations;
  47353. for (var index = 0; index < runtimeAnimations.length; index++) {
  47354. if (runtimeAnimations[index].animation.targetProperty === property) {
  47355. return runtimeAnimations[index].animation;
  47356. }
  47357. }
  47358. return null;
  47359. };
  47360. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  47361. var runtimeAnimations = this._runtimeAnimations;
  47362. for (var index = 0; index < runtimeAnimations.length; index++) {
  47363. if (runtimeAnimations[index].animation.targetProperty === property) {
  47364. return runtimeAnimations[index];
  47365. }
  47366. }
  47367. return null;
  47368. };
  47369. Animatable.prototype.reset = function () {
  47370. var runtimeAnimations = this._runtimeAnimations;
  47371. for (var index = 0; index < runtimeAnimations.length; index++) {
  47372. runtimeAnimations[index].reset();
  47373. }
  47374. // Reset to original value
  47375. for (index = 0; index < runtimeAnimations.length; index++) {
  47376. var animation = runtimeAnimations[index];
  47377. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  47378. }
  47379. this._localDelayOffset = null;
  47380. this._pausedDelay = null;
  47381. };
  47382. Animatable.prototype.enableBlending = function (blendingSpeed) {
  47383. var runtimeAnimations = this._runtimeAnimations;
  47384. for (var index = 0; index < runtimeAnimations.length; index++) {
  47385. runtimeAnimations[index].animation.enableBlending = true;
  47386. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  47387. }
  47388. };
  47389. Animatable.prototype.disableBlending = function () {
  47390. var runtimeAnimations = this._runtimeAnimations;
  47391. for (var index = 0; index < runtimeAnimations.length; index++) {
  47392. runtimeAnimations[index].animation.enableBlending = false;
  47393. }
  47394. };
  47395. Animatable.prototype.goToFrame = function (frame) {
  47396. var runtimeAnimations = this._runtimeAnimations;
  47397. if (runtimeAnimations[0]) {
  47398. var fps = runtimeAnimations[0].animation.framePerSecond;
  47399. var currentFrame = runtimeAnimations[0].currentFrame;
  47400. var adjustTime = frame - currentFrame;
  47401. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  47402. if (this._localDelayOffset === null) {
  47403. this._localDelayOffset = 0;
  47404. }
  47405. this._localDelayOffset -= delay;
  47406. }
  47407. for (var index = 0; index < runtimeAnimations.length; index++) {
  47408. runtimeAnimations[index].goToFrame(frame);
  47409. }
  47410. };
  47411. Animatable.prototype.pause = function () {
  47412. if (this._paused) {
  47413. return;
  47414. }
  47415. this._paused = true;
  47416. };
  47417. Animatable.prototype.restart = function () {
  47418. this._paused = false;
  47419. };
  47420. Animatable.prototype.stop = function (animationName) {
  47421. if (animationName) {
  47422. var idx = this._scene._activeAnimatables.indexOf(this);
  47423. if (idx > -1) {
  47424. var runtimeAnimations = this._runtimeAnimations;
  47425. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  47426. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  47427. continue;
  47428. }
  47429. runtimeAnimations[index].dispose();
  47430. runtimeAnimations.splice(index, 1);
  47431. }
  47432. if (runtimeAnimations.length == 0) {
  47433. this._scene._activeAnimatables.splice(idx, 1);
  47434. if (this.onAnimationEnd) {
  47435. this.onAnimationEnd();
  47436. }
  47437. }
  47438. }
  47439. }
  47440. else {
  47441. var index = this._scene._activeAnimatables.indexOf(this);
  47442. if (index > -1) {
  47443. this._scene._activeAnimatables.splice(index, 1);
  47444. var runtimeAnimations = this._runtimeAnimations;
  47445. for (var index = 0; index < runtimeAnimations.length; index++) {
  47446. runtimeAnimations[index].dispose();
  47447. }
  47448. if (this.onAnimationEnd) {
  47449. this.onAnimationEnd();
  47450. }
  47451. }
  47452. }
  47453. };
  47454. Animatable.prototype._animate = function (delay) {
  47455. if (this._paused) {
  47456. this.animationStarted = false;
  47457. if (this._pausedDelay === null) {
  47458. this._pausedDelay = delay;
  47459. }
  47460. return true;
  47461. }
  47462. if (this._localDelayOffset === null) {
  47463. this._localDelayOffset = delay;
  47464. this._pausedDelay = null;
  47465. }
  47466. else if (this._pausedDelay !== null) {
  47467. this._localDelayOffset += delay - this._pausedDelay;
  47468. this._pausedDelay = null;
  47469. }
  47470. // Animating
  47471. var running = false;
  47472. var runtimeAnimations = this._runtimeAnimations;
  47473. var index;
  47474. for (index = 0; index < runtimeAnimations.length; index++) {
  47475. var animation = runtimeAnimations[index];
  47476. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  47477. running = running || isRunning;
  47478. }
  47479. this.animationStarted = running;
  47480. if (!running) {
  47481. // Remove from active animatables
  47482. index = this._scene._activeAnimatables.indexOf(this);
  47483. this._scene._activeAnimatables.splice(index, 1);
  47484. // Dispose all runtime animations
  47485. for (index = 0; index < runtimeAnimations.length; index++) {
  47486. runtimeAnimations[index].dispose();
  47487. }
  47488. }
  47489. if (!running && this.onAnimationEnd) {
  47490. this.onAnimationEnd();
  47491. this.onAnimationEnd = null;
  47492. }
  47493. return running;
  47494. };
  47495. return Animatable;
  47496. }());
  47497. BABYLON.Animatable = Animatable;
  47498. })(BABYLON || (BABYLON = {}));
  47499. //# sourceMappingURL=babylon.animatable.js.map
  47500. var BABYLON;
  47501. (function (BABYLON) {
  47502. var EasingFunction = /** @class */ (function () {
  47503. function EasingFunction() {
  47504. // Properties
  47505. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  47506. }
  47507. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  47508. get: function () {
  47509. return EasingFunction._EASINGMODE_EASEIN;
  47510. },
  47511. enumerable: true,
  47512. configurable: true
  47513. });
  47514. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  47515. get: function () {
  47516. return EasingFunction._EASINGMODE_EASEOUT;
  47517. },
  47518. enumerable: true,
  47519. configurable: true
  47520. });
  47521. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  47522. get: function () {
  47523. return EasingFunction._EASINGMODE_EASEINOUT;
  47524. },
  47525. enumerable: true,
  47526. configurable: true
  47527. });
  47528. EasingFunction.prototype.setEasingMode = function (easingMode) {
  47529. var n = Math.min(Math.max(easingMode, 0), 2);
  47530. this._easingMode = n;
  47531. };
  47532. EasingFunction.prototype.getEasingMode = function () {
  47533. return this._easingMode;
  47534. };
  47535. EasingFunction.prototype.easeInCore = function (gradient) {
  47536. throw new Error('You must implement this method');
  47537. };
  47538. EasingFunction.prototype.ease = function (gradient) {
  47539. switch (this._easingMode) {
  47540. case EasingFunction.EASINGMODE_EASEIN:
  47541. return this.easeInCore(gradient);
  47542. case EasingFunction.EASINGMODE_EASEOUT:
  47543. return (1 - this.easeInCore(1 - gradient));
  47544. }
  47545. if (gradient >= 0.5) {
  47546. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  47547. }
  47548. return (this.easeInCore(gradient * 2) * 0.5);
  47549. };
  47550. //Statics
  47551. EasingFunction._EASINGMODE_EASEIN = 0;
  47552. EasingFunction._EASINGMODE_EASEOUT = 1;
  47553. EasingFunction._EASINGMODE_EASEINOUT = 2;
  47554. return EasingFunction;
  47555. }());
  47556. BABYLON.EasingFunction = EasingFunction;
  47557. var CircleEase = /** @class */ (function (_super) {
  47558. __extends(CircleEase, _super);
  47559. function CircleEase() {
  47560. return _super !== null && _super.apply(this, arguments) || this;
  47561. }
  47562. CircleEase.prototype.easeInCore = function (gradient) {
  47563. gradient = Math.max(0, Math.min(1, gradient));
  47564. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  47565. };
  47566. return CircleEase;
  47567. }(EasingFunction));
  47568. BABYLON.CircleEase = CircleEase;
  47569. var BackEase = /** @class */ (function (_super) {
  47570. __extends(BackEase, _super);
  47571. function BackEase(amplitude) {
  47572. if (amplitude === void 0) { amplitude = 1; }
  47573. var _this = _super.call(this) || this;
  47574. _this.amplitude = amplitude;
  47575. return _this;
  47576. }
  47577. BackEase.prototype.easeInCore = function (gradient) {
  47578. var num = Math.max(0, this.amplitude);
  47579. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  47580. };
  47581. return BackEase;
  47582. }(EasingFunction));
  47583. BABYLON.BackEase = BackEase;
  47584. var BounceEase = /** @class */ (function (_super) {
  47585. __extends(BounceEase, _super);
  47586. function BounceEase(bounces, bounciness) {
  47587. if (bounces === void 0) { bounces = 3; }
  47588. if (bounciness === void 0) { bounciness = 2; }
  47589. var _this = _super.call(this) || this;
  47590. _this.bounces = bounces;
  47591. _this.bounciness = bounciness;
  47592. return _this;
  47593. }
  47594. BounceEase.prototype.easeInCore = function (gradient) {
  47595. var y = Math.max(0.0, this.bounces);
  47596. var bounciness = this.bounciness;
  47597. if (bounciness <= 1.0) {
  47598. bounciness = 1.001;
  47599. }
  47600. var num9 = Math.pow(bounciness, y);
  47601. var num5 = 1.0 - bounciness;
  47602. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  47603. var num15 = gradient * num4;
  47604. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  47605. var num3 = Math.floor(num65);
  47606. var num13 = num3 + 1.0;
  47607. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  47608. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  47609. var num7 = (num8 + num12) * 0.5;
  47610. var num6 = gradient - num7;
  47611. var num2 = num7 - num8;
  47612. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  47613. };
  47614. return BounceEase;
  47615. }(EasingFunction));
  47616. BABYLON.BounceEase = BounceEase;
  47617. var CubicEase = /** @class */ (function (_super) {
  47618. __extends(CubicEase, _super);
  47619. function CubicEase() {
  47620. return _super !== null && _super.apply(this, arguments) || this;
  47621. }
  47622. CubicEase.prototype.easeInCore = function (gradient) {
  47623. return (gradient * gradient * gradient);
  47624. };
  47625. return CubicEase;
  47626. }(EasingFunction));
  47627. BABYLON.CubicEase = CubicEase;
  47628. var ElasticEase = /** @class */ (function (_super) {
  47629. __extends(ElasticEase, _super);
  47630. function ElasticEase(oscillations, springiness) {
  47631. if (oscillations === void 0) { oscillations = 3; }
  47632. if (springiness === void 0) { springiness = 3; }
  47633. var _this = _super.call(this) || this;
  47634. _this.oscillations = oscillations;
  47635. _this.springiness = springiness;
  47636. return _this;
  47637. }
  47638. ElasticEase.prototype.easeInCore = function (gradient) {
  47639. var num2;
  47640. var num3 = Math.max(0.0, this.oscillations);
  47641. var num = Math.max(0.0, this.springiness);
  47642. if (num == 0) {
  47643. num2 = gradient;
  47644. }
  47645. else {
  47646. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  47647. }
  47648. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  47649. };
  47650. return ElasticEase;
  47651. }(EasingFunction));
  47652. BABYLON.ElasticEase = ElasticEase;
  47653. var ExponentialEase = /** @class */ (function (_super) {
  47654. __extends(ExponentialEase, _super);
  47655. function ExponentialEase(exponent) {
  47656. if (exponent === void 0) { exponent = 2; }
  47657. var _this = _super.call(this) || this;
  47658. _this.exponent = exponent;
  47659. return _this;
  47660. }
  47661. ExponentialEase.prototype.easeInCore = function (gradient) {
  47662. if (this.exponent <= 0) {
  47663. return gradient;
  47664. }
  47665. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  47666. };
  47667. return ExponentialEase;
  47668. }(EasingFunction));
  47669. BABYLON.ExponentialEase = ExponentialEase;
  47670. var PowerEase = /** @class */ (function (_super) {
  47671. __extends(PowerEase, _super);
  47672. function PowerEase(power) {
  47673. if (power === void 0) { power = 2; }
  47674. var _this = _super.call(this) || this;
  47675. _this.power = power;
  47676. return _this;
  47677. }
  47678. PowerEase.prototype.easeInCore = function (gradient) {
  47679. var y = Math.max(0.0, this.power);
  47680. return Math.pow(gradient, y);
  47681. };
  47682. return PowerEase;
  47683. }(EasingFunction));
  47684. BABYLON.PowerEase = PowerEase;
  47685. var QuadraticEase = /** @class */ (function (_super) {
  47686. __extends(QuadraticEase, _super);
  47687. function QuadraticEase() {
  47688. return _super !== null && _super.apply(this, arguments) || this;
  47689. }
  47690. QuadraticEase.prototype.easeInCore = function (gradient) {
  47691. return (gradient * gradient);
  47692. };
  47693. return QuadraticEase;
  47694. }(EasingFunction));
  47695. BABYLON.QuadraticEase = QuadraticEase;
  47696. var QuarticEase = /** @class */ (function (_super) {
  47697. __extends(QuarticEase, _super);
  47698. function QuarticEase() {
  47699. return _super !== null && _super.apply(this, arguments) || this;
  47700. }
  47701. QuarticEase.prototype.easeInCore = function (gradient) {
  47702. return (gradient * gradient * gradient * gradient);
  47703. };
  47704. return QuarticEase;
  47705. }(EasingFunction));
  47706. BABYLON.QuarticEase = QuarticEase;
  47707. var QuinticEase = /** @class */ (function (_super) {
  47708. __extends(QuinticEase, _super);
  47709. function QuinticEase() {
  47710. return _super !== null && _super.apply(this, arguments) || this;
  47711. }
  47712. QuinticEase.prototype.easeInCore = function (gradient) {
  47713. return (gradient * gradient * gradient * gradient * gradient);
  47714. };
  47715. return QuinticEase;
  47716. }(EasingFunction));
  47717. BABYLON.QuinticEase = QuinticEase;
  47718. var SineEase = /** @class */ (function (_super) {
  47719. __extends(SineEase, _super);
  47720. function SineEase() {
  47721. return _super !== null && _super.apply(this, arguments) || this;
  47722. }
  47723. SineEase.prototype.easeInCore = function (gradient) {
  47724. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  47725. };
  47726. return SineEase;
  47727. }(EasingFunction));
  47728. BABYLON.SineEase = SineEase;
  47729. var BezierCurveEase = /** @class */ (function (_super) {
  47730. __extends(BezierCurveEase, _super);
  47731. function BezierCurveEase(x1, y1, x2, y2) {
  47732. if (x1 === void 0) { x1 = 0; }
  47733. if (y1 === void 0) { y1 = 0; }
  47734. if (x2 === void 0) { x2 = 1; }
  47735. if (y2 === void 0) { y2 = 1; }
  47736. var _this = _super.call(this) || this;
  47737. _this.x1 = x1;
  47738. _this.y1 = y1;
  47739. _this.x2 = x2;
  47740. _this.y2 = y2;
  47741. return _this;
  47742. }
  47743. BezierCurveEase.prototype.easeInCore = function (gradient) {
  47744. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  47745. };
  47746. return BezierCurveEase;
  47747. }(EasingFunction));
  47748. BABYLON.BezierCurveEase = BezierCurveEase;
  47749. })(BABYLON || (BABYLON = {}));
  47750. //# sourceMappingURL=babylon.easing.js.map
  47751. var BABYLON;
  47752. (function (BABYLON) {
  47753. var Condition = /** @class */ (function () {
  47754. function Condition(actionManager) {
  47755. this._actionManager = actionManager;
  47756. }
  47757. Condition.prototype.isValid = function () {
  47758. return true;
  47759. };
  47760. Condition.prototype._getProperty = function (propertyPath) {
  47761. return this._actionManager._getProperty(propertyPath);
  47762. };
  47763. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  47764. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47765. };
  47766. Condition.prototype.serialize = function () {
  47767. };
  47768. Condition.prototype._serialize = function (serializedCondition) {
  47769. return {
  47770. type: 2,
  47771. children: [],
  47772. name: serializedCondition.name,
  47773. properties: serializedCondition.properties
  47774. };
  47775. };
  47776. return Condition;
  47777. }());
  47778. BABYLON.Condition = Condition;
  47779. var ValueCondition = /** @class */ (function (_super) {
  47780. __extends(ValueCondition, _super);
  47781. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  47782. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  47783. var _this = _super.call(this, actionManager) || this;
  47784. _this.propertyPath = propertyPath;
  47785. _this.value = value;
  47786. _this.operator = operator;
  47787. _this._target = target;
  47788. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  47789. _this._property = _this._getProperty(_this.propertyPath);
  47790. return _this;
  47791. }
  47792. Object.defineProperty(ValueCondition, "IsEqual", {
  47793. get: function () {
  47794. return ValueCondition._IsEqual;
  47795. },
  47796. enumerable: true,
  47797. configurable: true
  47798. });
  47799. Object.defineProperty(ValueCondition, "IsDifferent", {
  47800. get: function () {
  47801. return ValueCondition._IsDifferent;
  47802. },
  47803. enumerable: true,
  47804. configurable: true
  47805. });
  47806. Object.defineProperty(ValueCondition, "IsGreater", {
  47807. get: function () {
  47808. return ValueCondition._IsGreater;
  47809. },
  47810. enumerable: true,
  47811. configurable: true
  47812. });
  47813. Object.defineProperty(ValueCondition, "IsLesser", {
  47814. get: function () {
  47815. return ValueCondition._IsLesser;
  47816. },
  47817. enumerable: true,
  47818. configurable: true
  47819. });
  47820. // Methods
  47821. ValueCondition.prototype.isValid = function () {
  47822. switch (this.operator) {
  47823. case ValueCondition.IsGreater:
  47824. return this._effectiveTarget[this._property] > this.value;
  47825. case ValueCondition.IsLesser:
  47826. return this._effectiveTarget[this._property] < this.value;
  47827. case ValueCondition.IsEqual:
  47828. case ValueCondition.IsDifferent:
  47829. var check;
  47830. if (this.value.equals) {
  47831. check = this.value.equals(this._effectiveTarget[this._property]);
  47832. }
  47833. else {
  47834. check = this.value === this._effectiveTarget[this._property];
  47835. }
  47836. return this.operator === ValueCondition.IsEqual ? check : !check;
  47837. }
  47838. return false;
  47839. };
  47840. ValueCondition.prototype.serialize = function () {
  47841. return this._serialize({
  47842. name: "ValueCondition",
  47843. properties: [
  47844. BABYLON.Action._GetTargetProperty(this._target),
  47845. { name: "propertyPath", value: this.propertyPath },
  47846. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  47847. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  47848. ]
  47849. });
  47850. };
  47851. ValueCondition.GetOperatorName = function (operator) {
  47852. switch (operator) {
  47853. case ValueCondition._IsEqual: return "IsEqual";
  47854. case ValueCondition._IsDifferent: return "IsDifferent";
  47855. case ValueCondition._IsGreater: return "IsGreater";
  47856. case ValueCondition._IsLesser: return "IsLesser";
  47857. default: return "";
  47858. }
  47859. };
  47860. // Statics
  47861. ValueCondition._IsEqual = 0;
  47862. ValueCondition._IsDifferent = 1;
  47863. ValueCondition._IsGreater = 2;
  47864. ValueCondition._IsLesser = 3;
  47865. return ValueCondition;
  47866. }(Condition));
  47867. BABYLON.ValueCondition = ValueCondition;
  47868. var PredicateCondition = /** @class */ (function (_super) {
  47869. __extends(PredicateCondition, _super);
  47870. function PredicateCondition(actionManager, predicate) {
  47871. var _this = _super.call(this, actionManager) || this;
  47872. _this.predicate = predicate;
  47873. return _this;
  47874. }
  47875. PredicateCondition.prototype.isValid = function () {
  47876. return this.predicate();
  47877. };
  47878. return PredicateCondition;
  47879. }(Condition));
  47880. BABYLON.PredicateCondition = PredicateCondition;
  47881. var StateCondition = /** @class */ (function (_super) {
  47882. __extends(StateCondition, _super);
  47883. function StateCondition(actionManager, target, value) {
  47884. var _this = _super.call(this, actionManager) || this;
  47885. _this.value = value;
  47886. _this._target = target;
  47887. return _this;
  47888. }
  47889. // Methods
  47890. StateCondition.prototype.isValid = function () {
  47891. return this._target.state === this.value;
  47892. };
  47893. StateCondition.prototype.serialize = function () {
  47894. return this._serialize({
  47895. name: "StateCondition",
  47896. properties: [
  47897. BABYLON.Action._GetTargetProperty(this._target),
  47898. { name: "value", value: this.value }
  47899. ]
  47900. });
  47901. };
  47902. return StateCondition;
  47903. }(Condition));
  47904. BABYLON.StateCondition = StateCondition;
  47905. })(BABYLON || (BABYLON = {}));
  47906. //# sourceMappingURL=babylon.condition.js.map
  47907. var BABYLON;
  47908. (function (BABYLON) {
  47909. var Action = /** @class */ (function () {
  47910. function Action(triggerOptions, condition) {
  47911. this.triggerOptions = triggerOptions;
  47912. this.onBeforeExecuteObservable = new BABYLON.Observable();
  47913. if (triggerOptions.parameter) {
  47914. this.trigger = triggerOptions.trigger;
  47915. this._triggerParameter = triggerOptions.parameter;
  47916. }
  47917. else {
  47918. this.trigger = triggerOptions;
  47919. }
  47920. this._nextActiveAction = this;
  47921. this._condition = condition;
  47922. }
  47923. // Methods
  47924. Action.prototype._prepare = function () {
  47925. };
  47926. Action.prototype.getTriggerParameter = function () {
  47927. return this._triggerParameter;
  47928. };
  47929. Action.prototype._executeCurrent = function (evt) {
  47930. if (this._nextActiveAction._condition) {
  47931. var condition = this._nextActiveAction._condition;
  47932. var currentRenderId = this._actionManager.getScene().getRenderId();
  47933. // We cache the current evaluation for the current frame
  47934. if (condition._evaluationId === currentRenderId) {
  47935. if (!condition._currentResult) {
  47936. return;
  47937. }
  47938. }
  47939. else {
  47940. condition._evaluationId = currentRenderId;
  47941. if (!condition.isValid()) {
  47942. condition._currentResult = false;
  47943. return;
  47944. }
  47945. condition._currentResult = true;
  47946. }
  47947. }
  47948. this.onBeforeExecuteObservable.notifyObservers(this);
  47949. this._nextActiveAction.execute(evt);
  47950. this.skipToNextActiveAction();
  47951. };
  47952. Action.prototype.execute = function (evt) {
  47953. };
  47954. Action.prototype.skipToNextActiveAction = function () {
  47955. if (this._nextActiveAction._child) {
  47956. if (!this._nextActiveAction._child._actionManager) {
  47957. this._nextActiveAction._child._actionManager = this._actionManager;
  47958. }
  47959. this._nextActiveAction = this._nextActiveAction._child;
  47960. }
  47961. else {
  47962. this._nextActiveAction = this;
  47963. }
  47964. };
  47965. Action.prototype.then = function (action) {
  47966. this._child = action;
  47967. action._actionManager = this._actionManager;
  47968. action._prepare();
  47969. return action;
  47970. };
  47971. Action.prototype._getProperty = function (propertyPath) {
  47972. return this._actionManager._getProperty(propertyPath);
  47973. };
  47974. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  47975. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47976. };
  47977. Action.prototype.serialize = function (parent) {
  47978. };
  47979. // Called by BABYLON.Action objects in serialize(...). Internal use
  47980. Action.prototype._serialize = function (serializedAction, parent) {
  47981. var serializationObject = {
  47982. type: 1,
  47983. children: [],
  47984. name: serializedAction.name,
  47985. properties: serializedAction.properties || []
  47986. };
  47987. // Serialize child
  47988. if (this._child) {
  47989. this._child.serialize(serializationObject);
  47990. }
  47991. // Check if "this" has a condition
  47992. if (this._condition) {
  47993. var serializedCondition = this._condition.serialize();
  47994. serializedCondition.children.push(serializationObject);
  47995. if (parent) {
  47996. parent.children.push(serializedCondition);
  47997. }
  47998. return serializedCondition;
  47999. }
  48000. if (parent) {
  48001. parent.children.push(serializationObject);
  48002. }
  48003. return serializationObject;
  48004. };
  48005. Action._SerializeValueAsString = function (value) {
  48006. if (typeof value === "number") {
  48007. return value.toString();
  48008. }
  48009. if (typeof value === "boolean") {
  48010. return value ? "true" : "false";
  48011. }
  48012. if (value instanceof BABYLON.Vector2) {
  48013. return value.x + ", " + value.y;
  48014. }
  48015. if (value instanceof BABYLON.Vector3) {
  48016. return value.x + ", " + value.y + ", " + value.z;
  48017. }
  48018. if (value instanceof BABYLON.Color3) {
  48019. return value.r + ", " + value.g + ", " + value.b;
  48020. }
  48021. if (value instanceof BABYLON.Color4) {
  48022. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  48023. }
  48024. return value; // string
  48025. };
  48026. Action._GetTargetProperty = function (target) {
  48027. return {
  48028. name: "target",
  48029. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  48030. : target instanceof BABYLON.Light ? "LightProperties"
  48031. : target instanceof BABYLON.Camera ? "CameraProperties"
  48032. : "SceneProperties",
  48033. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  48034. };
  48035. };
  48036. return Action;
  48037. }());
  48038. BABYLON.Action = Action;
  48039. })(BABYLON || (BABYLON = {}));
  48040. //# sourceMappingURL=babylon.action.js.map
  48041. var BABYLON;
  48042. (function (BABYLON) {
  48043. /**
  48044. * ActionEvent is the event beint sent when an action is triggered.
  48045. */
  48046. var ActionEvent = /** @class */ (function () {
  48047. /**
  48048. * @param source The mesh or sprite that triggered the action.
  48049. * @param pointerX The X mouse cursor position at the time of the event
  48050. * @param pointerY The Y mouse cursor position at the time of the event
  48051. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  48052. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  48053. */
  48054. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  48055. this.source = source;
  48056. this.pointerX = pointerX;
  48057. this.pointerY = pointerY;
  48058. this.meshUnderPointer = meshUnderPointer;
  48059. this.sourceEvent = sourceEvent;
  48060. this.additionalData = additionalData;
  48061. }
  48062. /**
  48063. * Helper function to auto-create an ActionEvent from a source mesh.
  48064. * @param source The source mesh that triggered the event
  48065. * @param evt {Event} The original (browser) event
  48066. */
  48067. ActionEvent.CreateNew = function (source, evt, additionalData) {
  48068. var scene = source.getScene();
  48069. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48070. };
  48071. /**
  48072. * Helper function to auto-create an ActionEvent from a source mesh.
  48073. * @param source The source sprite that triggered the event
  48074. * @param scene Scene associated with the sprite
  48075. * @param evt {Event} The original (browser) event
  48076. */
  48077. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  48078. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48079. };
  48080. /**
  48081. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  48082. * @param scene the scene where the event occurred
  48083. * @param evt {Event} The original (browser) event
  48084. */
  48085. ActionEvent.CreateNewFromScene = function (scene, evt) {
  48086. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  48087. };
  48088. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  48089. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  48090. };
  48091. return ActionEvent;
  48092. }());
  48093. BABYLON.ActionEvent = ActionEvent;
  48094. /**
  48095. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  48096. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  48097. */
  48098. var ActionManager = /** @class */ (function () {
  48099. function ActionManager(scene) {
  48100. // Members
  48101. this.actions = new Array();
  48102. this.hoverCursor = '';
  48103. this._scene = scene;
  48104. scene._actionManagers.push(this);
  48105. }
  48106. Object.defineProperty(ActionManager, "NothingTrigger", {
  48107. get: function () {
  48108. return ActionManager._NothingTrigger;
  48109. },
  48110. enumerable: true,
  48111. configurable: true
  48112. });
  48113. Object.defineProperty(ActionManager, "OnPickTrigger", {
  48114. get: function () {
  48115. return ActionManager._OnPickTrigger;
  48116. },
  48117. enumerable: true,
  48118. configurable: true
  48119. });
  48120. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  48121. get: function () {
  48122. return ActionManager._OnLeftPickTrigger;
  48123. },
  48124. enumerable: true,
  48125. configurable: true
  48126. });
  48127. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  48128. get: function () {
  48129. return ActionManager._OnRightPickTrigger;
  48130. },
  48131. enumerable: true,
  48132. configurable: true
  48133. });
  48134. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  48135. get: function () {
  48136. return ActionManager._OnCenterPickTrigger;
  48137. },
  48138. enumerable: true,
  48139. configurable: true
  48140. });
  48141. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  48142. get: function () {
  48143. return ActionManager._OnPickDownTrigger;
  48144. },
  48145. enumerable: true,
  48146. configurable: true
  48147. });
  48148. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  48149. get: function () {
  48150. return ActionManager._OnDoublePickTrigger;
  48151. },
  48152. enumerable: true,
  48153. configurable: true
  48154. });
  48155. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  48156. get: function () {
  48157. return ActionManager._OnPickUpTrigger;
  48158. },
  48159. enumerable: true,
  48160. configurable: true
  48161. });
  48162. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  48163. /// This trigger will only be raised if you also declared a OnPickDown
  48164. get: function () {
  48165. return ActionManager._OnPickOutTrigger;
  48166. },
  48167. enumerable: true,
  48168. configurable: true
  48169. });
  48170. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  48171. get: function () {
  48172. return ActionManager._OnLongPressTrigger;
  48173. },
  48174. enumerable: true,
  48175. configurable: true
  48176. });
  48177. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  48178. get: function () {
  48179. return ActionManager._OnPointerOverTrigger;
  48180. },
  48181. enumerable: true,
  48182. configurable: true
  48183. });
  48184. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  48185. get: function () {
  48186. return ActionManager._OnPointerOutTrigger;
  48187. },
  48188. enumerable: true,
  48189. configurable: true
  48190. });
  48191. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  48192. get: function () {
  48193. return ActionManager._OnEveryFrameTrigger;
  48194. },
  48195. enumerable: true,
  48196. configurable: true
  48197. });
  48198. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  48199. get: function () {
  48200. return ActionManager._OnIntersectionEnterTrigger;
  48201. },
  48202. enumerable: true,
  48203. configurable: true
  48204. });
  48205. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  48206. get: function () {
  48207. return ActionManager._OnIntersectionExitTrigger;
  48208. },
  48209. enumerable: true,
  48210. configurable: true
  48211. });
  48212. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  48213. get: function () {
  48214. return ActionManager._OnKeyDownTrigger;
  48215. },
  48216. enumerable: true,
  48217. configurable: true
  48218. });
  48219. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  48220. get: function () {
  48221. return ActionManager._OnKeyUpTrigger;
  48222. },
  48223. enumerable: true,
  48224. configurable: true
  48225. });
  48226. // Methods
  48227. ActionManager.prototype.dispose = function () {
  48228. var index = this._scene._actionManagers.indexOf(this);
  48229. for (var i = 0; i < this.actions.length; i++) {
  48230. var action = this.actions[i];
  48231. ActionManager.Triggers[action.trigger]--;
  48232. if (ActionManager.Triggers[action.trigger] === 0) {
  48233. delete ActionManager.Triggers[action.trigger];
  48234. }
  48235. }
  48236. if (index > -1) {
  48237. this._scene._actionManagers.splice(index, 1);
  48238. }
  48239. };
  48240. ActionManager.prototype.getScene = function () {
  48241. return this._scene;
  48242. };
  48243. /**
  48244. * Does this action manager handles actions of any of the given triggers
  48245. * @param {number[]} triggers - the triggers to be tested
  48246. * @return {boolean} whether one (or more) of the triggers is handeled
  48247. */
  48248. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  48249. for (var index = 0; index < this.actions.length; index++) {
  48250. var action = this.actions[index];
  48251. if (triggers.indexOf(action.trigger) > -1) {
  48252. return true;
  48253. }
  48254. }
  48255. return false;
  48256. };
  48257. /**
  48258. * Does this action manager handles actions of a given trigger
  48259. * @param {number} trigger - the trigger to be tested
  48260. * @return {boolean} whether the trigger is handeled
  48261. */
  48262. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  48263. for (var index = 0; index < this.actions.length; index++) {
  48264. var action = this.actions[index];
  48265. if (action.trigger === trigger) {
  48266. return true;
  48267. }
  48268. }
  48269. return false;
  48270. };
  48271. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  48272. /**
  48273. * Does this action manager has pointer triggers
  48274. * @return {boolean} whether or not it has pointer 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._OnPointerOutTrigger) {
  48280. return true;
  48281. }
  48282. }
  48283. return false;
  48284. },
  48285. enumerable: true,
  48286. configurable: true
  48287. });
  48288. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  48289. /**
  48290. * Does this action manager has pick triggers
  48291. * @return {boolean} whether or not it has pick triggers
  48292. */
  48293. get: function () {
  48294. for (var index = 0; index < this.actions.length; index++) {
  48295. var action = this.actions[index];
  48296. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  48297. return true;
  48298. }
  48299. }
  48300. return false;
  48301. },
  48302. enumerable: true,
  48303. configurable: true
  48304. });
  48305. Object.defineProperty(ActionManager, "HasTriggers", {
  48306. /**
  48307. * Does exist one action manager with at least one trigger
  48308. * @return {boolean} whether or not it exists one action manager with one trigger
  48309. **/
  48310. get: function () {
  48311. for (var t in ActionManager.Triggers) {
  48312. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48313. return true;
  48314. }
  48315. }
  48316. return false;
  48317. },
  48318. enumerable: true,
  48319. configurable: true
  48320. });
  48321. Object.defineProperty(ActionManager, "HasPickTriggers", {
  48322. /**
  48323. * Does exist one action manager with at least one pick trigger
  48324. * @return {boolean} whether or not it exists one action manager with one pick trigger
  48325. **/
  48326. get: function () {
  48327. for (var t in ActionManager.Triggers) {
  48328. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48329. var t_int = parseInt(t);
  48330. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  48331. return true;
  48332. }
  48333. }
  48334. }
  48335. return false;
  48336. },
  48337. enumerable: true,
  48338. configurable: true
  48339. });
  48340. /**
  48341. * Does exist one action manager that handles actions of a given trigger
  48342. * @param {number} trigger - the trigger to be tested
  48343. * @return {boolean} whether the trigger is handeled by at least one action manager
  48344. **/
  48345. ActionManager.HasSpecificTrigger = function (trigger) {
  48346. for (var t in ActionManager.Triggers) {
  48347. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48348. var t_int = parseInt(t);
  48349. if (t_int === trigger) {
  48350. return true;
  48351. }
  48352. }
  48353. }
  48354. return false;
  48355. };
  48356. /**
  48357. * Registers an action to this action manager
  48358. * @param {BABYLON.Action} action - the action to be registered
  48359. * @return {BABYLON.Action} the action amended (prepared) after registration
  48360. */
  48361. ActionManager.prototype.registerAction = function (action) {
  48362. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  48363. if (this.getScene().actionManager !== this) {
  48364. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  48365. return null;
  48366. }
  48367. }
  48368. this.actions.push(action);
  48369. if (ActionManager.Triggers[action.trigger]) {
  48370. ActionManager.Triggers[action.trigger]++;
  48371. }
  48372. else {
  48373. ActionManager.Triggers[action.trigger] = 1;
  48374. }
  48375. action._actionManager = this;
  48376. action._prepare();
  48377. return action;
  48378. };
  48379. /**
  48380. * Unregisters an action to this action manager
  48381. * @param action The action to be unregistered
  48382. * @return whether the action has been unregistered
  48383. */
  48384. ActionManager.prototype.unregisterAction = function (action) {
  48385. var index = this.actions.indexOf(action);
  48386. if (index !== -1) {
  48387. this.actions.splice(index, 1);
  48388. ActionManager.Triggers[action.trigger] -= 1;
  48389. if (ActionManager.Triggers[action.trigger] === 0) {
  48390. delete ActionManager.Triggers[action.trigger];
  48391. }
  48392. delete action._actionManager;
  48393. return true;
  48394. }
  48395. return false;
  48396. };
  48397. /**
  48398. * Process a specific trigger
  48399. * @param {number} trigger - the trigger to process
  48400. * @param evt {BABYLON.ActionEvent} the event details to be processed
  48401. */
  48402. ActionManager.prototype.processTrigger = function (trigger, evt) {
  48403. for (var index = 0; index < this.actions.length; index++) {
  48404. var action = this.actions[index];
  48405. if (action.trigger === trigger) {
  48406. if (evt) {
  48407. if (trigger === ActionManager.OnKeyUpTrigger
  48408. || trigger === ActionManager.OnKeyDownTrigger) {
  48409. var parameter = action.getTriggerParameter();
  48410. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  48411. if (!parameter.toLowerCase) {
  48412. continue;
  48413. }
  48414. var lowerCase = parameter.toLowerCase();
  48415. if (lowerCase !== evt.sourceEvent.key) {
  48416. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  48417. var actualkey = String.fromCharCode(unicode).toLowerCase();
  48418. if (actualkey !== lowerCase) {
  48419. continue;
  48420. }
  48421. }
  48422. }
  48423. }
  48424. }
  48425. action._executeCurrent(evt);
  48426. }
  48427. }
  48428. };
  48429. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  48430. var properties = propertyPath.split(".");
  48431. for (var index = 0; index < properties.length - 1; index++) {
  48432. target = target[properties[index]];
  48433. }
  48434. return target;
  48435. };
  48436. ActionManager.prototype._getProperty = function (propertyPath) {
  48437. var properties = propertyPath.split(".");
  48438. return properties[properties.length - 1];
  48439. };
  48440. ActionManager.prototype.serialize = function (name) {
  48441. var root = {
  48442. children: new Array(),
  48443. name: name,
  48444. type: 3,
  48445. properties: new Array() // Empty for root but required
  48446. };
  48447. for (var i = 0; i < this.actions.length; i++) {
  48448. var triggerObject = {
  48449. type: 0,
  48450. children: new Array(),
  48451. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  48452. properties: new Array()
  48453. };
  48454. var triggerOptions = this.actions[i].triggerOptions;
  48455. if (triggerOptions && typeof triggerOptions !== "number") {
  48456. if (triggerOptions.parameter instanceof BABYLON.Node) {
  48457. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  48458. }
  48459. else {
  48460. var parameter = {};
  48461. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  48462. if (triggerOptions.parameter.mesh) {
  48463. parameter._meshId = triggerOptions.parameter.mesh.id;
  48464. }
  48465. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  48466. }
  48467. }
  48468. // Serialize child action, recursively
  48469. this.actions[i].serialize(triggerObject);
  48470. // Add serialized trigger
  48471. root.children.push(triggerObject);
  48472. }
  48473. return root;
  48474. };
  48475. ActionManager.Parse = function (parsedActions, object, scene) {
  48476. var actionManager = new ActionManager(scene);
  48477. if (object === null)
  48478. scene.actionManager = actionManager;
  48479. else
  48480. object.actionManager = actionManager;
  48481. // instanciate a new object
  48482. var instanciate = function (name, params) {
  48483. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  48484. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  48485. newInstance.constructor.apply(newInstance, params);
  48486. return newInstance;
  48487. };
  48488. var parseParameter = function (name, value, target, propertyPath) {
  48489. if (propertyPath === null) {
  48490. // String, boolean or float
  48491. var floatValue = parseFloat(value);
  48492. if (value === "true" || value === "false")
  48493. return value === "true";
  48494. else
  48495. return isNaN(floatValue) ? value : floatValue;
  48496. }
  48497. var effectiveTarget = propertyPath.split(".");
  48498. var values = value.split(",");
  48499. // Get effective Target
  48500. for (var i = 0; i < effectiveTarget.length; i++) {
  48501. target = target[effectiveTarget[i]];
  48502. }
  48503. // Return appropriate value with its type
  48504. if (typeof (target) === "boolean")
  48505. return values[0] === "true";
  48506. if (typeof (target) === "string")
  48507. return values[0];
  48508. // Parameters with multiple values such as Vector3 etc.
  48509. var split = new Array();
  48510. for (var i = 0; i < values.length; i++)
  48511. split.push(parseFloat(values[i]));
  48512. if (target instanceof BABYLON.Vector3)
  48513. return BABYLON.Vector3.FromArray(split);
  48514. if (target instanceof BABYLON.Vector4)
  48515. return BABYLON.Vector4.FromArray(split);
  48516. if (target instanceof BABYLON.Color3)
  48517. return BABYLON.Color3.FromArray(split);
  48518. if (target instanceof BABYLON.Color4)
  48519. return BABYLON.Color4.FromArray(split);
  48520. return parseFloat(values[0]);
  48521. };
  48522. // traverse graph per trigger
  48523. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  48524. if (combineArray === void 0) { combineArray = null; }
  48525. if (parsedAction.detached)
  48526. return;
  48527. var parameters = new Array();
  48528. var target = null;
  48529. var propertyPath = null;
  48530. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  48531. // Parameters
  48532. if (parsedAction.type === 2)
  48533. parameters.push(actionManager);
  48534. else
  48535. parameters.push(trigger);
  48536. if (combine) {
  48537. var actions = new Array();
  48538. for (var j = 0; j < parsedAction.combine.length; j++) {
  48539. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  48540. }
  48541. parameters.push(actions);
  48542. }
  48543. else {
  48544. for (var i = 0; i < parsedAction.properties.length; i++) {
  48545. var value = parsedAction.properties[i].value;
  48546. var name = parsedAction.properties[i].name;
  48547. var targetType = parsedAction.properties[i].targetType;
  48548. if (name === "target")
  48549. if (targetType !== null && targetType === "SceneProperties")
  48550. value = target = scene;
  48551. else
  48552. value = target = scene.getNodeByName(value);
  48553. else if (name === "parent")
  48554. value = scene.getNodeByName(value);
  48555. else if (name === "sound")
  48556. value = scene.getSoundByName(value);
  48557. else if (name !== "propertyPath") {
  48558. if (parsedAction.type === 2 && name === "operator")
  48559. value = BABYLON.ValueCondition[value];
  48560. else
  48561. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  48562. }
  48563. else {
  48564. propertyPath = value;
  48565. }
  48566. parameters.push(value);
  48567. }
  48568. }
  48569. if (combineArray === null) {
  48570. parameters.push(condition);
  48571. }
  48572. else {
  48573. parameters.push(null);
  48574. }
  48575. // If interpolate value action
  48576. if (parsedAction.name === "InterpolateValueAction") {
  48577. var param = parameters[parameters.length - 2];
  48578. parameters[parameters.length - 1] = param;
  48579. parameters[parameters.length - 2] = condition;
  48580. }
  48581. // Action or condition(s) and not CombineAction
  48582. var newAction = instanciate(parsedAction.name, parameters);
  48583. if (newAction instanceof BABYLON.Condition && condition !== null) {
  48584. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  48585. if (action)
  48586. action.then(nothing);
  48587. else
  48588. actionManager.registerAction(nothing);
  48589. action = nothing;
  48590. }
  48591. if (combineArray === null) {
  48592. if (newAction instanceof BABYLON.Condition) {
  48593. condition = newAction;
  48594. newAction = action;
  48595. }
  48596. else {
  48597. condition = null;
  48598. if (action)
  48599. action.then(newAction);
  48600. else
  48601. actionManager.registerAction(newAction);
  48602. }
  48603. }
  48604. else {
  48605. combineArray.push(newAction);
  48606. }
  48607. for (var i = 0; i < parsedAction.children.length; i++)
  48608. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  48609. };
  48610. // triggers
  48611. for (var i = 0; i < parsedActions.children.length; i++) {
  48612. var triggerParams;
  48613. var trigger = parsedActions.children[i];
  48614. if (trigger.properties.length > 0) {
  48615. var param = trigger.properties[0].value;
  48616. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  48617. if (value._meshId) {
  48618. value.mesh = scene.getMeshByID(value._meshId);
  48619. }
  48620. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  48621. }
  48622. else
  48623. triggerParams = ActionManager[trigger.name];
  48624. for (var j = 0; j < trigger.children.length; j++) {
  48625. if (!trigger.detached)
  48626. traverse(trigger.children[j], triggerParams, null, null);
  48627. }
  48628. }
  48629. };
  48630. ActionManager.GetTriggerName = function (trigger) {
  48631. switch (trigger) {
  48632. case 0: return "NothingTrigger";
  48633. case 1: return "OnPickTrigger";
  48634. case 2: return "OnLeftPickTrigger";
  48635. case 3: return "OnRightPickTrigger";
  48636. case 4: return "OnCenterPickTrigger";
  48637. case 5: return "OnPickDownTrigger";
  48638. case 6: return "OnPickUpTrigger";
  48639. case 7: return "OnLongPressTrigger";
  48640. case 8: return "OnPointerOverTrigger";
  48641. case 9: return "OnPointerOutTrigger";
  48642. case 10: return "OnEveryFrameTrigger";
  48643. case 11: return "OnIntersectionEnterTrigger";
  48644. case 12: return "OnIntersectionExitTrigger";
  48645. case 13: return "OnKeyDownTrigger";
  48646. case 14: return "OnKeyUpTrigger";
  48647. case 15: return "OnPickOutTrigger";
  48648. default: return "";
  48649. }
  48650. };
  48651. // Statics
  48652. ActionManager._NothingTrigger = 0;
  48653. ActionManager._OnPickTrigger = 1;
  48654. ActionManager._OnLeftPickTrigger = 2;
  48655. ActionManager._OnRightPickTrigger = 3;
  48656. ActionManager._OnCenterPickTrigger = 4;
  48657. ActionManager._OnPickDownTrigger = 5;
  48658. ActionManager._OnDoublePickTrigger = 6;
  48659. ActionManager._OnPickUpTrigger = 7;
  48660. ActionManager._OnLongPressTrigger = 8;
  48661. ActionManager._OnPointerOverTrigger = 9;
  48662. ActionManager._OnPointerOutTrigger = 10;
  48663. ActionManager._OnEveryFrameTrigger = 11;
  48664. ActionManager._OnIntersectionEnterTrigger = 12;
  48665. ActionManager._OnIntersectionExitTrigger = 13;
  48666. ActionManager._OnKeyDownTrigger = 14;
  48667. ActionManager._OnKeyUpTrigger = 15;
  48668. ActionManager._OnPickOutTrigger = 16;
  48669. ActionManager.Triggers = {};
  48670. return ActionManager;
  48671. }());
  48672. BABYLON.ActionManager = ActionManager;
  48673. })(BABYLON || (BABYLON = {}));
  48674. //# sourceMappingURL=babylon.actionManager.js.map
  48675. var BABYLON;
  48676. (function (BABYLON) {
  48677. var InterpolateValueAction = /** @class */ (function (_super) {
  48678. __extends(InterpolateValueAction, _super);
  48679. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  48680. if (duration === void 0) { duration = 1000; }
  48681. var _this = _super.call(this, triggerOptions, condition) || this;
  48682. _this.propertyPath = propertyPath;
  48683. _this.value = value;
  48684. _this.duration = duration;
  48685. _this.stopOtherAnimations = stopOtherAnimations;
  48686. _this.onInterpolationDone = onInterpolationDone;
  48687. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  48688. _this._target = _this._effectiveTarget = target;
  48689. return _this;
  48690. }
  48691. InterpolateValueAction.prototype._prepare = function () {
  48692. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48693. this._property = this._getProperty(this.propertyPath);
  48694. };
  48695. InterpolateValueAction.prototype.execute = function () {
  48696. var _this = this;
  48697. var scene = this._actionManager.getScene();
  48698. var keys = [
  48699. {
  48700. frame: 0,
  48701. value: this._effectiveTarget[this._property]
  48702. }, {
  48703. frame: 100,
  48704. value: this.value
  48705. }
  48706. ];
  48707. var dataType;
  48708. if (typeof this.value === "number") {
  48709. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  48710. }
  48711. else if (this.value instanceof BABYLON.Color3) {
  48712. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  48713. }
  48714. else if (this.value instanceof BABYLON.Vector3) {
  48715. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  48716. }
  48717. else if (this.value instanceof BABYLON.Matrix) {
  48718. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  48719. }
  48720. else if (this.value instanceof BABYLON.Quaternion) {
  48721. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  48722. }
  48723. else {
  48724. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  48725. return;
  48726. }
  48727. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  48728. animation.setKeys(keys);
  48729. if (this.stopOtherAnimations) {
  48730. scene.stopAnimation(this._effectiveTarget);
  48731. }
  48732. var wrapper = function () {
  48733. _this.onInterpolationDoneObservable.notifyObservers(_this);
  48734. if (_this.onInterpolationDone) {
  48735. _this.onInterpolationDone();
  48736. }
  48737. };
  48738. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  48739. };
  48740. InterpolateValueAction.prototype.serialize = function (parent) {
  48741. return _super.prototype._serialize.call(this, {
  48742. name: "InterpolateValueAction",
  48743. properties: [
  48744. BABYLON.Action._GetTargetProperty(this._target),
  48745. { name: "propertyPath", value: this.propertyPath },
  48746. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48747. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  48748. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  48749. ]
  48750. }, parent);
  48751. };
  48752. return InterpolateValueAction;
  48753. }(BABYLON.Action));
  48754. BABYLON.InterpolateValueAction = InterpolateValueAction;
  48755. })(BABYLON || (BABYLON = {}));
  48756. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  48757. var BABYLON;
  48758. (function (BABYLON) {
  48759. var SwitchBooleanAction = /** @class */ (function (_super) {
  48760. __extends(SwitchBooleanAction, _super);
  48761. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  48762. var _this = _super.call(this, triggerOptions, condition) || this;
  48763. _this.propertyPath = propertyPath;
  48764. _this._target = _this._effectiveTarget = target;
  48765. return _this;
  48766. }
  48767. SwitchBooleanAction.prototype._prepare = function () {
  48768. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48769. this._property = this._getProperty(this.propertyPath);
  48770. };
  48771. SwitchBooleanAction.prototype.execute = function () {
  48772. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  48773. };
  48774. SwitchBooleanAction.prototype.serialize = function (parent) {
  48775. return _super.prototype._serialize.call(this, {
  48776. name: "SwitchBooleanAction",
  48777. properties: [
  48778. BABYLON.Action._GetTargetProperty(this._target),
  48779. { name: "propertyPath", value: this.propertyPath }
  48780. ]
  48781. }, parent);
  48782. };
  48783. return SwitchBooleanAction;
  48784. }(BABYLON.Action));
  48785. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  48786. var SetStateAction = /** @class */ (function (_super) {
  48787. __extends(SetStateAction, _super);
  48788. function SetStateAction(triggerOptions, target, value, condition) {
  48789. var _this = _super.call(this, triggerOptions, condition) || this;
  48790. _this.value = value;
  48791. _this._target = target;
  48792. return _this;
  48793. }
  48794. SetStateAction.prototype.execute = function () {
  48795. this._target.state = this.value;
  48796. };
  48797. SetStateAction.prototype.serialize = function (parent) {
  48798. return _super.prototype._serialize.call(this, {
  48799. name: "SetStateAction",
  48800. properties: [
  48801. BABYLON.Action._GetTargetProperty(this._target),
  48802. { name: "value", value: this.value }
  48803. ]
  48804. }, parent);
  48805. };
  48806. return SetStateAction;
  48807. }(BABYLON.Action));
  48808. BABYLON.SetStateAction = SetStateAction;
  48809. var SetValueAction = /** @class */ (function (_super) {
  48810. __extends(SetValueAction, _super);
  48811. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  48812. var _this = _super.call(this, triggerOptions, condition) || this;
  48813. _this.propertyPath = propertyPath;
  48814. _this.value = value;
  48815. _this._target = _this._effectiveTarget = target;
  48816. return _this;
  48817. }
  48818. SetValueAction.prototype._prepare = function () {
  48819. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48820. this._property = this._getProperty(this.propertyPath);
  48821. };
  48822. SetValueAction.prototype.execute = function () {
  48823. this._effectiveTarget[this._property] = this.value;
  48824. if (this._target.markAsDirty) {
  48825. this._target.markAsDirty(this._property);
  48826. }
  48827. };
  48828. SetValueAction.prototype.serialize = function (parent) {
  48829. return _super.prototype._serialize.call(this, {
  48830. name: "SetValueAction",
  48831. properties: [
  48832. BABYLON.Action._GetTargetProperty(this._target),
  48833. { name: "propertyPath", value: this.propertyPath },
  48834. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48835. ]
  48836. }, parent);
  48837. };
  48838. return SetValueAction;
  48839. }(BABYLON.Action));
  48840. BABYLON.SetValueAction = SetValueAction;
  48841. var IncrementValueAction = /** @class */ (function (_super) {
  48842. __extends(IncrementValueAction, _super);
  48843. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  48844. var _this = _super.call(this, triggerOptions, condition) || this;
  48845. _this.propertyPath = propertyPath;
  48846. _this.value = value;
  48847. _this._target = _this._effectiveTarget = target;
  48848. return _this;
  48849. }
  48850. IncrementValueAction.prototype._prepare = function () {
  48851. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48852. this._property = this._getProperty(this.propertyPath);
  48853. if (typeof this._effectiveTarget[this._property] !== "number") {
  48854. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  48855. }
  48856. };
  48857. IncrementValueAction.prototype.execute = function () {
  48858. this._effectiveTarget[this._property] += this.value;
  48859. if (this._target.markAsDirty) {
  48860. this._target.markAsDirty(this._property);
  48861. }
  48862. };
  48863. IncrementValueAction.prototype.serialize = function (parent) {
  48864. return _super.prototype._serialize.call(this, {
  48865. name: "IncrementValueAction",
  48866. properties: [
  48867. BABYLON.Action._GetTargetProperty(this._target),
  48868. { name: "propertyPath", value: this.propertyPath },
  48869. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48870. ]
  48871. }, parent);
  48872. };
  48873. return IncrementValueAction;
  48874. }(BABYLON.Action));
  48875. BABYLON.IncrementValueAction = IncrementValueAction;
  48876. var PlayAnimationAction = /** @class */ (function (_super) {
  48877. __extends(PlayAnimationAction, _super);
  48878. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  48879. var _this = _super.call(this, triggerOptions, condition) || this;
  48880. _this.from = from;
  48881. _this.to = to;
  48882. _this.loop = loop;
  48883. _this._target = target;
  48884. return _this;
  48885. }
  48886. PlayAnimationAction.prototype._prepare = function () {
  48887. };
  48888. PlayAnimationAction.prototype.execute = function () {
  48889. var scene = this._actionManager.getScene();
  48890. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  48891. };
  48892. PlayAnimationAction.prototype.serialize = function (parent) {
  48893. return _super.prototype._serialize.call(this, {
  48894. name: "PlayAnimationAction",
  48895. properties: [
  48896. BABYLON.Action._GetTargetProperty(this._target),
  48897. { name: "from", value: String(this.from) },
  48898. { name: "to", value: String(this.to) },
  48899. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  48900. ]
  48901. }, parent);
  48902. };
  48903. return PlayAnimationAction;
  48904. }(BABYLON.Action));
  48905. BABYLON.PlayAnimationAction = PlayAnimationAction;
  48906. var StopAnimationAction = /** @class */ (function (_super) {
  48907. __extends(StopAnimationAction, _super);
  48908. function StopAnimationAction(triggerOptions, target, condition) {
  48909. var _this = _super.call(this, triggerOptions, condition) || this;
  48910. _this._target = target;
  48911. return _this;
  48912. }
  48913. StopAnimationAction.prototype._prepare = function () {
  48914. };
  48915. StopAnimationAction.prototype.execute = function () {
  48916. var scene = this._actionManager.getScene();
  48917. scene.stopAnimation(this._target);
  48918. };
  48919. StopAnimationAction.prototype.serialize = function (parent) {
  48920. return _super.prototype._serialize.call(this, {
  48921. name: "StopAnimationAction",
  48922. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  48923. }, parent);
  48924. };
  48925. return StopAnimationAction;
  48926. }(BABYLON.Action));
  48927. BABYLON.StopAnimationAction = StopAnimationAction;
  48928. var DoNothingAction = /** @class */ (function (_super) {
  48929. __extends(DoNothingAction, _super);
  48930. function DoNothingAction(triggerOptions, condition) {
  48931. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  48932. return _super.call(this, triggerOptions, condition) || this;
  48933. }
  48934. DoNothingAction.prototype.execute = function () {
  48935. };
  48936. DoNothingAction.prototype.serialize = function (parent) {
  48937. return _super.prototype._serialize.call(this, {
  48938. name: "DoNothingAction",
  48939. properties: []
  48940. }, parent);
  48941. };
  48942. return DoNothingAction;
  48943. }(BABYLON.Action));
  48944. BABYLON.DoNothingAction = DoNothingAction;
  48945. var CombineAction = /** @class */ (function (_super) {
  48946. __extends(CombineAction, _super);
  48947. function CombineAction(triggerOptions, children, condition) {
  48948. var _this = _super.call(this, triggerOptions, condition) || this;
  48949. _this.children = children;
  48950. return _this;
  48951. }
  48952. CombineAction.prototype._prepare = function () {
  48953. for (var index = 0; index < this.children.length; index++) {
  48954. this.children[index]._actionManager = this._actionManager;
  48955. this.children[index]._prepare();
  48956. }
  48957. };
  48958. CombineAction.prototype.execute = function (evt) {
  48959. for (var index = 0; index < this.children.length; index++) {
  48960. this.children[index].execute(evt);
  48961. }
  48962. };
  48963. CombineAction.prototype.serialize = function (parent) {
  48964. var serializationObject = _super.prototype._serialize.call(this, {
  48965. name: "CombineAction",
  48966. properties: [],
  48967. combine: []
  48968. }, parent);
  48969. for (var i = 0; i < this.children.length; i++) {
  48970. serializationObject.combine.push(this.children[i].serialize(null));
  48971. }
  48972. return serializationObject;
  48973. };
  48974. return CombineAction;
  48975. }(BABYLON.Action));
  48976. BABYLON.CombineAction = CombineAction;
  48977. var ExecuteCodeAction = /** @class */ (function (_super) {
  48978. __extends(ExecuteCodeAction, _super);
  48979. function ExecuteCodeAction(triggerOptions, func, condition) {
  48980. var _this = _super.call(this, triggerOptions, condition) || this;
  48981. _this.func = func;
  48982. return _this;
  48983. }
  48984. ExecuteCodeAction.prototype.execute = function (evt) {
  48985. this.func(evt);
  48986. };
  48987. return ExecuteCodeAction;
  48988. }(BABYLON.Action));
  48989. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  48990. var SetParentAction = /** @class */ (function (_super) {
  48991. __extends(SetParentAction, _super);
  48992. function SetParentAction(triggerOptions, target, parent, condition) {
  48993. var _this = _super.call(this, triggerOptions, condition) || this;
  48994. _this._target = target;
  48995. _this._parent = parent;
  48996. return _this;
  48997. }
  48998. SetParentAction.prototype._prepare = function () {
  48999. };
  49000. SetParentAction.prototype.execute = function () {
  49001. if (this._target.parent === this._parent) {
  49002. return;
  49003. }
  49004. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  49005. invertParentWorldMatrix.invert();
  49006. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  49007. this._target.parent = this._parent;
  49008. };
  49009. SetParentAction.prototype.serialize = function (parent) {
  49010. return _super.prototype._serialize.call(this, {
  49011. name: "SetParentAction",
  49012. properties: [
  49013. BABYLON.Action._GetTargetProperty(this._target),
  49014. BABYLON.Action._GetTargetProperty(this._parent),
  49015. ]
  49016. }, parent);
  49017. };
  49018. return SetParentAction;
  49019. }(BABYLON.Action));
  49020. BABYLON.SetParentAction = SetParentAction;
  49021. var PlaySoundAction = /** @class */ (function (_super) {
  49022. __extends(PlaySoundAction, _super);
  49023. function PlaySoundAction(triggerOptions, sound, condition) {
  49024. var _this = _super.call(this, triggerOptions, condition) || this;
  49025. _this._sound = sound;
  49026. return _this;
  49027. }
  49028. PlaySoundAction.prototype._prepare = function () {
  49029. };
  49030. PlaySoundAction.prototype.execute = function () {
  49031. if (this._sound !== undefined)
  49032. this._sound.play();
  49033. };
  49034. PlaySoundAction.prototype.serialize = function (parent) {
  49035. return _super.prototype._serialize.call(this, {
  49036. name: "PlaySoundAction",
  49037. properties: [{ name: "sound", value: this._sound.name }]
  49038. }, parent);
  49039. };
  49040. return PlaySoundAction;
  49041. }(BABYLON.Action));
  49042. BABYLON.PlaySoundAction = PlaySoundAction;
  49043. var StopSoundAction = /** @class */ (function (_super) {
  49044. __extends(StopSoundAction, _super);
  49045. function StopSoundAction(triggerOptions, sound, condition) {
  49046. var _this = _super.call(this, triggerOptions, condition) || this;
  49047. _this._sound = sound;
  49048. return _this;
  49049. }
  49050. StopSoundAction.prototype._prepare = function () {
  49051. };
  49052. StopSoundAction.prototype.execute = function () {
  49053. if (this._sound !== undefined)
  49054. this._sound.stop();
  49055. };
  49056. StopSoundAction.prototype.serialize = function (parent) {
  49057. return _super.prototype._serialize.call(this, {
  49058. name: "StopSoundAction",
  49059. properties: [{ name: "sound", value: this._sound.name }]
  49060. }, parent);
  49061. };
  49062. return StopSoundAction;
  49063. }(BABYLON.Action));
  49064. BABYLON.StopSoundAction = StopSoundAction;
  49065. })(BABYLON || (BABYLON = {}));
  49066. //# sourceMappingURL=babylon.directActions.js.map
  49067. var BABYLON;
  49068. (function (BABYLON) {
  49069. var SpriteManager = /** @class */ (function () {
  49070. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  49071. if (epsilon === void 0) { epsilon = 0.01; }
  49072. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49073. this.name = name;
  49074. this.sprites = new Array();
  49075. this.renderingGroupId = 0;
  49076. this.layerMask = 0x0FFFFFFF;
  49077. this.fogEnabled = true;
  49078. this.isPickable = false;
  49079. /**
  49080. * An event triggered when the manager is disposed.
  49081. * @type {BABYLON.Observable}
  49082. */
  49083. this.onDisposeObservable = new BABYLON.Observable();
  49084. this._vertexBuffers = {};
  49085. this._capacity = capacity;
  49086. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  49087. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49088. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49089. if (cellSize.width && cellSize.height) {
  49090. this.cellWidth = cellSize.width;
  49091. this.cellHeight = cellSize.height;
  49092. }
  49093. else if (cellSize !== undefined) {
  49094. this.cellWidth = cellSize;
  49095. this.cellHeight = cellSize;
  49096. }
  49097. else {
  49098. return;
  49099. }
  49100. this._epsilon = epsilon;
  49101. this._scene = scene;
  49102. this._scene.spriteManagers.push(this);
  49103. var indices = [];
  49104. var index = 0;
  49105. for (var count = 0; count < capacity; count++) {
  49106. indices.push(index);
  49107. indices.push(index + 1);
  49108. indices.push(index + 2);
  49109. indices.push(index);
  49110. indices.push(index + 2);
  49111. indices.push(index + 3);
  49112. index += 4;
  49113. }
  49114. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  49115. // VBO
  49116. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  49117. this._vertexData = new Float32Array(capacity * 16 * 4);
  49118. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  49119. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  49120. var options = this._buffer.createVertexBuffer("options", 4, 4);
  49121. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  49122. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  49123. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  49124. this._vertexBuffers["options"] = options;
  49125. this._vertexBuffers["cellInfo"] = cellInfo;
  49126. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  49127. // Effects
  49128. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  49129. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  49130. }
  49131. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  49132. set: function (callback) {
  49133. if (this._onDisposeObserver) {
  49134. this.onDisposeObservable.remove(this._onDisposeObserver);
  49135. }
  49136. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  49137. },
  49138. enumerable: true,
  49139. configurable: true
  49140. });
  49141. Object.defineProperty(SpriteManager.prototype, "texture", {
  49142. get: function () {
  49143. return this._spriteTexture;
  49144. },
  49145. set: function (value) {
  49146. this._spriteTexture = value;
  49147. },
  49148. enumerable: true,
  49149. configurable: true
  49150. });
  49151. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  49152. var arrayOffset = index * 16;
  49153. if (offsetX === 0)
  49154. offsetX = this._epsilon;
  49155. else if (offsetX === 1)
  49156. offsetX = 1 - this._epsilon;
  49157. if (offsetY === 0)
  49158. offsetY = this._epsilon;
  49159. else if (offsetY === 1)
  49160. offsetY = 1 - this._epsilon;
  49161. this._vertexData[arrayOffset] = sprite.position.x;
  49162. this._vertexData[arrayOffset + 1] = sprite.position.y;
  49163. this._vertexData[arrayOffset + 2] = sprite.position.z;
  49164. this._vertexData[arrayOffset + 3] = sprite.angle;
  49165. this._vertexData[arrayOffset + 4] = sprite.width;
  49166. this._vertexData[arrayOffset + 5] = sprite.height;
  49167. this._vertexData[arrayOffset + 6] = offsetX;
  49168. this._vertexData[arrayOffset + 7] = offsetY;
  49169. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  49170. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  49171. var offset = (sprite.cellIndex / rowSize) >> 0;
  49172. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  49173. this._vertexData[arrayOffset + 11] = offset;
  49174. // Color
  49175. this._vertexData[arrayOffset + 12] = sprite.color.r;
  49176. this._vertexData[arrayOffset + 13] = sprite.color.g;
  49177. this._vertexData[arrayOffset + 14] = sprite.color.b;
  49178. this._vertexData[arrayOffset + 15] = sprite.color.a;
  49179. };
  49180. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  49181. var count = Math.min(this._capacity, this.sprites.length);
  49182. var min = BABYLON.Vector3.Zero();
  49183. var max = BABYLON.Vector3.Zero();
  49184. var distance = Number.MAX_VALUE;
  49185. var currentSprite = null;
  49186. var cameraSpacePosition = BABYLON.Vector3.Zero();
  49187. var cameraView = camera.getViewMatrix();
  49188. for (var index = 0; index < count; index++) {
  49189. var sprite = this.sprites[index];
  49190. if (!sprite) {
  49191. continue;
  49192. }
  49193. if (predicate) {
  49194. if (!predicate(sprite)) {
  49195. continue;
  49196. }
  49197. }
  49198. else if (!sprite.isPickable) {
  49199. continue;
  49200. }
  49201. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  49202. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  49203. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  49204. if (ray.intersectsBoxMinMax(min, max)) {
  49205. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  49206. if (distance > currentDistance) {
  49207. distance = currentDistance;
  49208. currentSprite = sprite;
  49209. if (fastCheck) {
  49210. break;
  49211. }
  49212. }
  49213. }
  49214. }
  49215. if (currentSprite) {
  49216. var result = new BABYLON.PickingInfo();
  49217. result.hit = true;
  49218. result.pickedSprite = currentSprite;
  49219. result.distance = distance;
  49220. return result;
  49221. }
  49222. return null;
  49223. };
  49224. SpriteManager.prototype.render = function () {
  49225. // Check
  49226. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  49227. return;
  49228. var engine = this._scene.getEngine();
  49229. var baseSize = this._spriteTexture.getBaseSize();
  49230. // Sprites
  49231. var deltaTime = engine.getDeltaTime();
  49232. var max = Math.min(this._capacity, this.sprites.length);
  49233. var rowSize = baseSize.width / this.cellWidth;
  49234. var offset = 0;
  49235. for (var index = 0; index < max; index++) {
  49236. var sprite = this.sprites[index];
  49237. if (!sprite) {
  49238. continue;
  49239. }
  49240. sprite._animate(deltaTime);
  49241. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  49242. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  49243. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  49244. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  49245. }
  49246. this._buffer.update(this._vertexData);
  49247. // Render
  49248. var effect = this._effectBase;
  49249. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49250. effect = this._effectFog;
  49251. }
  49252. engine.enableEffect(effect);
  49253. var viewMatrix = this._scene.getViewMatrix();
  49254. effect.setTexture("diffuseSampler", this._spriteTexture);
  49255. effect.setMatrix("view", viewMatrix);
  49256. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  49257. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  49258. // Fog
  49259. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49260. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  49261. effect.setColor3("vFogColor", this._scene.fogColor);
  49262. }
  49263. // VBOs
  49264. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  49265. // Draw order
  49266. engine.setDepthFunctionToLessOrEqual();
  49267. effect.setBool("alphaTest", true);
  49268. engine.setColorWrite(false);
  49269. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49270. engine.setColorWrite(true);
  49271. effect.setBool("alphaTest", false);
  49272. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  49273. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49274. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  49275. };
  49276. SpriteManager.prototype.dispose = function () {
  49277. if (this._buffer) {
  49278. this._buffer.dispose();
  49279. this._buffer = null;
  49280. }
  49281. if (this._indexBuffer) {
  49282. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  49283. this._indexBuffer = null;
  49284. }
  49285. if (this._spriteTexture) {
  49286. this._spriteTexture.dispose();
  49287. this._spriteTexture = null;
  49288. }
  49289. // Remove from scene
  49290. var index = this._scene.spriteManagers.indexOf(this);
  49291. this._scene.spriteManagers.splice(index, 1);
  49292. // Callback
  49293. this.onDisposeObservable.notifyObservers(this);
  49294. this.onDisposeObservable.clear();
  49295. };
  49296. return SpriteManager;
  49297. }());
  49298. BABYLON.SpriteManager = SpriteManager;
  49299. })(BABYLON || (BABYLON = {}));
  49300. //# sourceMappingURL=babylon.spriteManager.js.map
  49301. var BABYLON;
  49302. (function (BABYLON) {
  49303. var Sprite = /** @class */ (function () {
  49304. function Sprite(name, manager) {
  49305. this.name = name;
  49306. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49307. this.width = 1.0;
  49308. this.height = 1.0;
  49309. this.angle = 0;
  49310. this.cellIndex = 0;
  49311. this.invertU = 0;
  49312. this.invertV = 0;
  49313. this.animations = new Array();
  49314. this.isPickable = false;
  49315. this._animationStarted = false;
  49316. this._loopAnimation = false;
  49317. this._fromIndex = 0;
  49318. this._toIndex = 0;
  49319. this._delay = 0;
  49320. this._direction = 1;
  49321. this._time = 0;
  49322. this._manager = manager;
  49323. this._manager.sprites.push(this);
  49324. this.position = BABYLON.Vector3.Zero();
  49325. }
  49326. Object.defineProperty(Sprite.prototype, "size", {
  49327. get: function () {
  49328. return this.width;
  49329. },
  49330. set: function (value) {
  49331. this.width = value;
  49332. this.height = value;
  49333. },
  49334. enumerable: true,
  49335. configurable: true
  49336. });
  49337. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  49338. this._fromIndex = from;
  49339. this._toIndex = to;
  49340. this._loopAnimation = loop;
  49341. this._delay = delay;
  49342. this._animationStarted = true;
  49343. this._direction = from < to ? 1 : -1;
  49344. this.cellIndex = from;
  49345. this._time = 0;
  49346. this._onAnimationEnd = onAnimationEnd;
  49347. };
  49348. Sprite.prototype.stopAnimation = function () {
  49349. this._animationStarted = false;
  49350. };
  49351. Sprite.prototype._animate = function (deltaTime) {
  49352. if (!this._animationStarted)
  49353. return;
  49354. this._time += deltaTime;
  49355. if (this._time > this._delay) {
  49356. this._time = this._time % this._delay;
  49357. this.cellIndex += this._direction;
  49358. if (this.cellIndex > this._toIndex) {
  49359. if (this._loopAnimation) {
  49360. this.cellIndex = this._fromIndex;
  49361. }
  49362. else {
  49363. this.cellIndex = this._toIndex;
  49364. this._animationStarted = false;
  49365. if (this._onAnimationEnd) {
  49366. this._onAnimationEnd();
  49367. }
  49368. if (this.disposeWhenFinishedAnimating) {
  49369. this.dispose();
  49370. }
  49371. }
  49372. }
  49373. }
  49374. };
  49375. Sprite.prototype.dispose = function () {
  49376. for (var i = 0; i < this._manager.sprites.length; i++) {
  49377. if (this._manager.sprites[i] == this) {
  49378. this._manager.sprites.splice(i, 1);
  49379. }
  49380. }
  49381. };
  49382. return Sprite;
  49383. }());
  49384. BABYLON.Sprite = Sprite;
  49385. })(BABYLON || (BABYLON = {}));
  49386. //# sourceMappingURL=babylon.sprite.js.map
  49387. var BABYLON;
  49388. (function (BABYLON) {
  49389. var IntersectionInfo = /** @class */ (function () {
  49390. function IntersectionInfo(bu, bv, distance) {
  49391. this.bu = bu;
  49392. this.bv = bv;
  49393. this.distance = distance;
  49394. this.faceId = 0;
  49395. this.subMeshId = 0;
  49396. }
  49397. return IntersectionInfo;
  49398. }());
  49399. BABYLON.IntersectionInfo = IntersectionInfo;
  49400. var PickingInfo = /** @class */ (function () {
  49401. function PickingInfo() {
  49402. this.hit = false;
  49403. this.distance = 0;
  49404. this.pickedPoint = null;
  49405. this.pickedMesh = null;
  49406. this.bu = 0;
  49407. this.bv = 0;
  49408. this.faceId = -1;
  49409. this.subMeshId = 0;
  49410. this.pickedSprite = null;
  49411. }
  49412. // Methods
  49413. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  49414. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  49415. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  49416. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  49417. return null;
  49418. }
  49419. var indices = this.pickedMesh.getIndices();
  49420. if (!indices) {
  49421. return null;
  49422. }
  49423. var result;
  49424. if (useVerticesNormals) {
  49425. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49426. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  49427. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  49428. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  49429. normal0 = normal0.scale(this.bu);
  49430. normal1 = normal1.scale(this.bv);
  49431. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  49432. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  49433. }
  49434. else {
  49435. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49436. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  49437. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  49438. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  49439. var p1p2 = vertex1.subtract(vertex2);
  49440. var p3p2 = vertex3.subtract(vertex2);
  49441. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  49442. }
  49443. if (useWorldCoordinates) {
  49444. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  49445. }
  49446. return BABYLON.Vector3.Normalize(result);
  49447. };
  49448. PickingInfo.prototype.getTextureCoordinates = function () {
  49449. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49450. return null;
  49451. }
  49452. var indices = this.pickedMesh.getIndices();
  49453. if (!indices) {
  49454. return null;
  49455. }
  49456. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49457. if (!uvs) {
  49458. return null;
  49459. }
  49460. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  49461. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  49462. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  49463. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  49464. uv1 = uv1.scale(this.bu);
  49465. uv2 = uv2.scale(this.bv);
  49466. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  49467. };
  49468. return PickingInfo;
  49469. }());
  49470. BABYLON.PickingInfo = PickingInfo;
  49471. })(BABYLON || (BABYLON = {}));
  49472. //# sourceMappingURL=babylon.pickingInfo.js.map
  49473. var BABYLON;
  49474. (function (BABYLON) {
  49475. var Ray = /** @class */ (function () {
  49476. function Ray(origin, direction, length) {
  49477. if (length === void 0) { length = Number.MAX_VALUE; }
  49478. this.origin = origin;
  49479. this.direction = direction;
  49480. this.length = length;
  49481. }
  49482. // Methods
  49483. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  49484. var d = 0.0;
  49485. var maxValue = Number.MAX_VALUE;
  49486. var inv;
  49487. var min;
  49488. var max;
  49489. var temp;
  49490. if (Math.abs(this.direction.x) < 0.0000001) {
  49491. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  49492. return false;
  49493. }
  49494. }
  49495. else {
  49496. inv = 1.0 / this.direction.x;
  49497. min = (minimum.x - this.origin.x) * inv;
  49498. max = (maximum.x - this.origin.x) * inv;
  49499. if (max === -Infinity) {
  49500. max = Infinity;
  49501. }
  49502. if (min > max) {
  49503. temp = min;
  49504. min = max;
  49505. max = temp;
  49506. }
  49507. d = Math.max(min, d);
  49508. maxValue = Math.min(max, maxValue);
  49509. if (d > maxValue) {
  49510. return false;
  49511. }
  49512. }
  49513. if (Math.abs(this.direction.y) < 0.0000001) {
  49514. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  49515. return false;
  49516. }
  49517. }
  49518. else {
  49519. inv = 1.0 / this.direction.y;
  49520. min = (minimum.y - this.origin.y) * inv;
  49521. max = (maximum.y - this.origin.y) * inv;
  49522. if (max === -Infinity) {
  49523. max = Infinity;
  49524. }
  49525. if (min > max) {
  49526. temp = min;
  49527. min = max;
  49528. max = temp;
  49529. }
  49530. d = Math.max(min, d);
  49531. maxValue = Math.min(max, maxValue);
  49532. if (d > maxValue) {
  49533. return false;
  49534. }
  49535. }
  49536. if (Math.abs(this.direction.z) < 0.0000001) {
  49537. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  49538. return false;
  49539. }
  49540. }
  49541. else {
  49542. inv = 1.0 / this.direction.z;
  49543. min = (minimum.z - this.origin.z) * inv;
  49544. max = (maximum.z - this.origin.z) * inv;
  49545. if (max === -Infinity) {
  49546. max = Infinity;
  49547. }
  49548. if (min > max) {
  49549. temp = min;
  49550. min = max;
  49551. max = temp;
  49552. }
  49553. d = Math.max(min, d);
  49554. maxValue = Math.min(max, maxValue);
  49555. if (d > maxValue) {
  49556. return false;
  49557. }
  49558. }
  49559. return true;
  49560. };
  49561. Ray.prototype.intersectsBox = function (box) {
  49562. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  49563. };
  49564. Ray.prototype.intersectsSphere = function (sphere) {
  49565. var x = sphere.center.x - this.origin.x;
  49566. var y = sphere.center.y - this.origin.y;
  49567. var z = sphere.center.z - this.origin.z;
  49568. var pyth = (x * x) + (y * y) + (z * z);
  49569. var rr = sphere.radius * sphere.radius;
  49570. if (pyth <= rr) {
  49571. return true;
  49572. }
  49573. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  49574. if (dot < 0.0) {
  49575. return false;
  49576. }
  49577. var temp = pyth - (dot * dot);
  49578. return temp <= rr;
  49579. };
  49580. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  49581. if (!this._edge1) {
  49582. this._edge1 = BABYLON.Vector3.Zero();
  49583. this._edge2 = BABYLON.Vector3.Zero();
  49584. this._pvec = BABYLON.Vector3.Zero();
  49585. this._tvec = BABYLON.Vector3.Zero();
  49586. this._qvec = BABYLON.Vector3.Zero();
  49587. }
  49588. vertex1.subtractToRef(vertex0, this._edge1);
  49589. vertex2.subtractToRef(vertex0, this._edge2);
  49590. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  49591. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  49592. if (det === 0) {
  49593. return null;
  49594. }
  49595. var invdet = 1 / det;
  49596. this.origin.subtractToRef(vertex0, this._tvec);
  49597. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  49598. if (bu < 0 || bu > 1.0) {
  49599. return null;
  49600. }
  49601. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  49602. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  49603. if (bv < 0 || bu + bv > 1.0) {
  49604. return null;
  49605. }
  49606. //check if the distance is longer than the predefined length.
  49607. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  49608. if (distance > this.length) {
  49609. return null;
  49610. }
  49611. return new BABYLON.IntersectionInfo(bu, bv, distance);
  49612. };
  49613. Ray.prototype.intersectsPlane = function (plane) {
  49614. var distance;
  49615. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  49616. if (Math.abs(result1) < 9.99999997475243E-07) {
  49617. return null;
  49618. }
  49619. else {
  49620. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  49621. distance = (-plane.d - result2) / result1;
  49622. if (distance < 0.0) {
  49623. if (distance < -9.99999997475243E-07) {
  49624. return null;
  49625. }
  49626. else {
  49627. return 0;
  49628. }
  49629. }
  49630. return distance;
  49631. }
  49632. };
  49633. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  49634. var tm = BABYLON.Tmp.Matrix[0];
  49635. mesh.getWorldMatrix().invertToRef(tm);
  49636. if (this._tmpRay) {
  49637. Ray.TransformToRef(this, tm, this._tmpRay);
  49638. }
  49639. else {
  49640. this._tmpRay = Ray.Transform(this, tm);
  49641. }
  49642. return mesh.intersects(this._tmpRay, fastCheck);
  49643. };
  49644. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  49645. if (results) {
  49646. results.length = 0;
  49647. }
  49648. else {
  49649. results = [];
  49650. }
  49651. for (var i = 0; i < meshes.length; i++) {
  49652. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  49653. if (pickInfo.hit) {
  49654. results.push(pickInfo);
  49655. }
  49656. }
  49657. results.sort(this._comparePickingInfo);
  49658. return results;
  49659. };
  49660. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  49661. if (pickingInfoA.distance < pickingInfoB.distance) {
  49662. return -1;
  49663. }
  49664. else if (pickingInfoA.distance > pickingInfoB.distance) {
  49665. return 1;
  49666. }
  49667. else {
  49668. return 0;
  49669. }
  49670. };
  49671. /**
  49672. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  49673. * @param sega the first point of the segment to test the intersection against
  49674. * @param segb the second point of the segment to test the intersection against
  49675. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  49676. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  49677. */
  49678. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  49679. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  49680. var u = segb.subtract(sega);
  49681. var v = rsegb.subtract(this.origin);
  49682. var w = sega.subtract(this.origin);
  49683. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  49684. var b = BABYLON.Vector3.Dot(u, v);
  49685. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  49686. var d = BABYLON.Vector3.Dot(u, w);
  49687. var e = BABYLON.Vector3.Dot(v, w);
  49688. var D = a * c - b * b; // always >= 0
  49689. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  49690. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  49691. // compute the line parameters of the two closest points
  49692. if (D < Ray.smallnum) {
  49693. sN = 0.0; // force using point P0 on segment S1
  49694. sD = 1.0; // to prevent possible division by 0.0 later
  49695. tN = e;
  49696. tD = c;
  49697. }
  49698. else {
  49699. sN = (b * e - c * d);
  49700. tN = (a * e - b * d);
  49701. if (sN < 0.0) {
  49702. sN = 0.0;
  49703. tN = e;
  49704. tD = c;
  49705. }
  49706. else if (sN > sD) {
  49707. sN = sD;
  49708. tN = e + b;
  49709. tD = c;
  49710. }
  49711. }
  49712. if (tN < 0.0) {
  49713. tN = 0.0;
  49714. // recompute sc for this edge
  49715. if (-d < 0.0) {
  49716. sN = 0.0;
  49717. }
  49718. else if (-d > a)
  49719. sN = sD;
  49720. else {
  49721. sN = -d;
  49722. sD = a;
  49723. }
  49724. }
  49725. else if (tN > tD) {
  49726. tN = tD;
  49727. // recompute sc for this edge
  49728. if ((-d + b) < 0.0) {
  49729. sN = 0;
  49730. }
  49731. else if ((-d + b) > a) {
  49732. sN = sD;
  49733. }
  49734. else {
  49735. sN = (-d + b);
  49736. sD = a;
  49737. }
  49738. }
  49739. // finally do the division to get sc and tc
  49740. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  49741. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  49742. // get the difference of the two closest points
  49743. var qtc = v.multiplyByFloats(tc, tc, tc);
  49744. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  49745. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  49746. if (isIntersected) {
  49747. return qtc.length();
  49748. }
  49749. return -1;
  49750. };
  49751. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49752. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  49753. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  49754. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  49755. this.direction.normalize();
  49756. return this;
  49757. };
  49758. // Statics
  49759. Ray.Zero = function () {
  49760. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  49761. };
  49762. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49763. var result = Ray.Zero();
  49764. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  49765. };
  49766. /**
  49767. * 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
  49768. * transformed to the given world matrix.
  49769. * @param origin The origin point
  49770. * @param end The end point
  49771. * @param world a matrix to transform the ray to. Default is the identity matrix.
  49772. */
  49773. Ray.CreateNewFromTo = function (origin, end, world) {
  49774. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  49775. var direction = end.subtract(origin);
  49776. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  49777. direction.normalize();
  49778. return Ray.Transform(new Ray(origin, direction, length), world);
  49779. };
  49780. Ray.Transform = function (ray, matrix) {
  49781. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  49782. Ray.TransformToRef(ray, matrix, result);
  49783. return result;
  49784. };
  49785. Ray.TransformToRef = function (ray, matrix, result) {
  49786. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  49787. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  49788. result.length = ray.length;
  49789. var dir = result.direction;
  49790. var len = dir.length();
  49791. if (!(len === 0 || len === 1)) {
  49792. var num = 1.0 / len;
  49793. dir.x *= num;
  49794. dir.y *= num;
  49795. dir.z *= num;
  49796. result.length *= len;
  49797. }
  49798. };
  49799. Ray.smallnum = 0.00000001;
  49800. Ray.rayl = 10e8;
  49801. return Ray;
  49802. }());
  49803. BABYLON.Ray = Ray;
  49804. })(BABYLON || (BABYLON = {}));
  49805. //# sourceMappingURL=babylon.ray.js.map
  49806. var BABYLON;
  49807. (function (BABYLON) {
  49808. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  49809. if (boxMin.x > sphereCenter.x + sphereRadius)
  49810. return false;
  49811. if (sphereCenter.x - sphereRadius > boxMax.x)
  49812. return false;
  49813. if (boxMin.y > sphereCenter.y + sphereRadius)
  49814. return false;
  49815. if (sphereCenter.y - sphereRadius > boxMax.y)
  49816. return false;
  49817. if (boxMin.z > sphereCenter.z + sphereRadius)
  49818. return false;
  49819. if (sphereCenter.z - sphereRadius > boxMax.z)
  49820. return false;
  49821. return true;
  49822. };
  49823. var getLowestRoot = (function () {
  49824. var result = { root: 0, found: false };
  49825. return function (a, b, c, maxR) {
  49826. result.root = 0;
  49827. result.found = false;
  49828. var determinant = b * b - 4.0 * a * c;
  49829. if (determinant < 0)
  49830. return result;
  49831. var sqrtD = Math.sqrt(determinant);
  49832. var r1 = (-b - sqrtD) / (2.0 * a);
  49833. var r2 = (-b + sqrtD) / (2.0 * a);
  49834. if (r1 > r2) {
  49835. var temp = r2;
  49836. r2 = r1;
  49837. r1 = temp;
  49838. }
  49839. if (r1 > 0 && r1 < maxR) {
  49840. result.root = r1;
  49841. result.found = true;
  49842. return result;
  49843. }
  49844. if (r2 > 0 && r2 < maxR) {
  49845. result.root = r2;
  49846. result.found = true;
  49847. return result;
  49848. }
  49849. return result;
  49850. };
  49851. })();
  49852. var Collider = /** @class */ (function () {
  49853. function Collider() {
  49854. this._collisionPoint = BABYLON.Vector3.Zero();
  49855. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  49856. this._tempVector = BABYLON.Vector3.Zero();
  49857. this._tempVector2 = BABYLON.Vector3.Zero();
  49858. this._tempVector3 = BABYLON.Vector3.Zero();
  49859. this._tempVector4 = BABYLON.Vector3.Zero();
  49860. this._edge = BABYLON.Vector3.Zero();
  49861. this._baseToVertex = BABYLON.Vector3.Zero();
  49862. this._destinationPoint = BABYLON.Vector3.Zero();
  49863. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  49864. this._displacementVector = BABYLON.Vector3.Zero();
  49865. this._radius = BABYLON.Vector3.One();
  49866. this._retry = 0;
  49867. this._basePointWorld = BABYLON.Vector3.Zero();
  49868. this._velocityWorld = BABYLON.Vector3.Zero();
  49869. this._normalizedVelocity = BABYLON.Vector3.Zero();
  49870. this._collisionMask = -1;
  49871. }
  49872. Object.defineProperty(Collider.prototype, "collisionMask", {
  49873. get: function () {
  49874. return this._collisionMask;
  49875. },
  49876. set: function (mask) {
  49877. this._collisionMask = !isNaN(mask) ? mask : -1;
  49878. },
  49879. enumerable: true,
  49880. configurable: true
  49881. });
  49882. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  49883. /**
  49884. * Gets the plane normal used to compute the sliding response (in local space)
  49885. */
  49886. get: function () {
  49887. return this._slidePlaneNormal;
  49888. },
  49889. enumerable: true,
  49890. configurable: true
  49891. });
  49892. // Methods
  49893. Collider.prototype._initialize = function (source, dir, e) {
  49894. this._velocity = dir;
  49895. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  49896. this._basePoint = source;
  49897. source.multiplyToRef(this._radius, this._basePointWorld);
  49898. dir.multiplyToRef(this._radius, this._velocityWorld);
  49899. this._velocityWorldLength = this._velocityWorld.length();
  49900. this._epsilon = e;
  49901. this.collisionFound = false;
  49902. };
  49903. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  49904. pa.subtractToRef(point, this._tempVector);
  49905. pb.subtractToRef(point, this._tempVector2);
  49906. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  49907. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49908. if (d < 0)
  49909. return false;
  49910. pc.subtractToRef(point, this._tempVector3);
  49911. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  49912. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49913. if (d < 0)
  49914. return false;
  49915. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  49916. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49917. return d >= 0;
  49918. };
  49919. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  49920. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  49921. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  49922. if (distance > this._velocityWorldLength + max + sphereRadius) {
  49923. return false;
  49924. }
  49925. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  49926. return false;
  49927. return true;
  49928. };
  49929. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  49930. var t0;
  49931. var embeddedInPlane = false;
  49932. //defensive programming, actually not needed.
  49933. if (!trianglePlaneArray) {
  49934. trianglePlaneArray = [];
  49935. }
  49936. if (!trianglePlaneArray[faceIndex]) {
  49937. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  49938. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  49939. }
  49940. var trianglePlane = trianglePlaneArray[faceIndex];
  49941. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  49942. return;
  49943. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  49944. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  49945. if (normalDotVelocity == 0) {
  49946. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  49947. return;
  49948. embeddedInPlane = true;
  49949. t0 = 0;
  49950. }
  49951. else {
  49952. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49953. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49954. if (t0 > t1) {
  49955. var temp = t1;
  49956. t1 = t0;
  49957. t0 = temp;
  49958. }
  49959. if (t0 > 1.0 || t1 < 0.0)
  49960. return;
  49961. if (t0 < 0)
  49962. t0 = 0;
  49963. if (t0 > 1.0)
  49964. t0 = 1.0;
  49965. }
  49966. this._collisionPoint.copyFromFloats(0, 0, 0);
  49967. var found = false;
  49968. var t = 1.0;
  49969. if (!embeddedInPlane) {
  49970. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  49971. this._velocity.scaleToRef(t0, this._tempVector);
  49972. this._planeIntersectionPoint.addInPlace(this._tempVector);
  49973. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  49974. found = true;
  49975. t = t0;
  49976. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  49977. }
  49978. }
  49979. if (!found) {
  49980. var velocitySquaredLength = this._velocity.lengthSquared();
  49981. var a = velocitySquaredLength;
  49982. this._basePoint.subtractToRef(p1, this._tempVector);
  49983. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49984. var c = this._tempVector.lengthSquared() - 1.0;
  49985. var lowestRoot = getLowestRoot(a, b, c, t);
  49986. if (lowestRoot.found) {
  49987. t = lowestRoot.root;
  49988. found = true;
  49989. this._collisionPoint.copyFrom(p1);
  49990. }
  49991. this._basePoint.subtractToRef(p2, this._tempVector);
  49992. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49993. c = this._tempVector.lengthSquared() - 1.0;
  49994. lowestRoot = getLowestRoot(a, b, c, t);
  49995. if (lowestRoot.found) {
  49996. t = lowestRoot.root;
  49997. found = true;
  49998. this._collisionPoint.copyFrom(p2);
  49999. }
  50000. this._basePoint.subtractToRef(p3, this._tempVector);
  50001. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50002. c = this._tempVector.lengthSquared() - 1.0;
  50003. lowestRoot = getLowestRoot(a, b, c, t);
  50004. if (lowestRoot.found) {
  50005. t = lowestRoot.root;
  50006. found = true;
  50007. this._collisionPoint.copyFrom(p3);
  50008. }
  50009. p2.subtractToRef(p1, this._edge);
  50010. p1.subtractToRef(this._basePoint, this._baseToVertex);
  50011. var edgeSquaredLength = this._edge.lengthSquared();
  50012. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50013. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50014. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50015. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50016. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50017. lowestRoot = getLowestRoot(a, b, c, t);
  50018. if (lowestRoot.found) {
  50019. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50020. if (f >= 0.0 && f <= 1.0) {
  50021. t = lowestRoot.root;
  50022. found = true;
  50023. this._edge.scaleInPlace(f);
  50024. p1.addToRef(this._edge, this._collisionPoint);
  50025. }
  50026. }
  50027. p3.subtractToRef(p2, this._edge);
  50028. p2.subtractToRef(this._basePoint, this._baseToVertex);
  50029. edgeSquaredLength = this._edge.lengthSquared();
  50030. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50031. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50032. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50033. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50034. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50035. lowestRoot = getLowestRoot(a, b, c, t);
  50036. if (lowestRoot.found) {
  50037. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50038. if (f >= 0.0 && f <= 1.0) {
  50039. t = lowestRoot.root;
  50040. found = true;
  50041. this._edge.scaleInPlace(f);
  50042. p2.addToRef(this._edge, this._collisionPoint);
  50043. }
  50044. }
  50045. p1.subtractToRef(p3, this._edge);
  50046. p3.subtractToRef(this._basePoint, this._baseToVertex);
  50047. edgeSquaredLength = this._edge.lengthSquared();
  50048. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50049. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50050. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50051. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50052. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50053. lowestRoot = getLowestRoot(a, b, c, t);
  50054. if (lowestRoot.found) {
  50055. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50056. if (f >= 0.0 && f <= 1.0) {
  50057. t = lowestRoot.root;
  50058. found = true;
  50059. this._edge.scaleInPlace(f);
  50060. p3.addToRef(this._edge, this._collisionPoint);
  50061. }
  50062. }
  50063. }
  50064. if (found) {
  50065. var distToCollision = t * this._velocity.length();
  50066. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  50067. if (!this.intersectionPoint) {
  50068. this.intersectionPoint = this._collisionPoint.clone();
  50069. }
  50070. else {
  50071. this.intersectionPoint.copyFrom(this._collisionPoint);
  50072. }
  50073. this._nearestDistance = distToCollision;
  50074. this.collisionFound = true;
  50075. }
  50076. }
  50077. };
  50078. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  50079. for (var i = indexStart; i < indexEnd; i += 3) {
  50080. var p1 = pts[indices[i] - decal];
  50081. var p2 = pts[indices[i + 1] - decal];
  50082. var p3 = pts[indices[i + 2] - decal];
  50083. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  50084. }
  50085. };
  50086. Collider.prototype._getResponse = function (pos, vel) {
  50087. pos.addToRef(vel, this._destinationPoint);
  50088. vel.scaleInPlace((this._nearestDistance / vel.length()));
  50089. this._basePoint.addToRef(vel, pos);
  50090. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  50091. this._slidePlaneNormal.normalize();
  50092. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  50093. pos.addInPlace(this._displacementVector);
  50094. this.intersectionPoint.addInPlace(this._displacementVector);
  50095. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  50096. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  50097. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  50098. };
  50099. return Collider;
  50100. }());
  50101. BABYLON.Collider = Collider;
  50102. })(BABYLON || (BABYLON = {}));
  50103. //# sourceMappingURL=babylon.collider.js.map
  50104. var BABYLON;
  50105. (function (BABYLON) {
  50106. //WebWorker code will be inserted to this variable.
  50107. BABYLON.CollisionWorker = "";
  50108. var WorkerTaskType;
  50109. (function (WorkerTaskType) {
  50110. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  50111. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  50112. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  50113. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  50114. var WorkerReplyType;
  50115. (function (WorkerReplyType) {
  50116. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  50117. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  50118. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  50119. var CollisionCoordinatorWorker = /** @class */ (function () {
  50120. function CollisionCoordinatorWorker() {
  50121. var _this = this;
  50122. this._scaledPosition = BABYLON.Vector3.Zero();
  50123. this._scaledVelocity = BABYLON.Vector3.Zero();
  50124. this.onMeshUpdated = function (transformNode) {
  50125. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  50126. };
  50127. this.onGeometryUpdated = function (geometry) {
  50128. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  50129. };
  50130. this._afterRender = function () {
  50131. if (!_this._init)
  50132. return;
  50133. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  50134. return;
  50135. }
  50136. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  50137. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  50138. if (_this._runningUpdated > 4) {
  50139. return;
  50140. }
  50141. ++_this._runningUpdated;
  50142. var payload = {
  50143. updatedMeshes: _this._addUpdateMeshesList,
  50144. updatedGeometries: _this._addUpdateGeometriesList,
  50145. removedGeometries: _this._toRemoveGeometryArray,
  50146. removedMeshes: _this._toRemoveMeshesArray
  50147. };
  50148. var message = {
  50149. payload: payload,
  50150. taskType: WorkerTaskType.UPDATE
  50151. };
  50152. var serializable = [];
  50153. for (var id in payload.updatedGeometries) {
  50154. if (payload.updatedGeometries.hasOwnProperty(id)) {
  50155. //prepare transferables
  50156. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  50157. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  50158. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  50159. }
  50160. }
  50161. _this._worker.postMessage(message, serializable);
  50162. _this._addUpdateMeshesList = {};
  50163. _this._addUpdateGeometriesList = {};
  50164. _this._toRemoveGeometryArray = [];
  50165. _this._toRemoveMeshesArray = [];
  50166. };
  50167. this._onMessageFromWorker = function (e) {
  50168. var returnData = e.data;
  50169. if (returnData.error != WorkerReplyType.SUCCESS) {
  50170. //TODO what errors can be returned from the worker?
  50171. BABYLON.Tools.Warn("error returned from worker!");
  50172. return;
  50173. }
  50174. switch (returnData.taskType) {
  50175. case WorkerTaskType.INIT:
  50176. _this._init = true;
  50177. //Update the worked with ALL of the scene's current state
  50178. _this._scene.meshes.forEach(function (mesh) {
  50179. _this.onMeshAdded(mesh);
  50180. });
  50181. _this._scene.getGeometries().forEach(function (geometry) {
  50182. _this.onGeometryAdded(geometry);
  50183. });
  50184. break;
  50185. case WorkerTaskType.UPDATE:
  50186. _this._runningUpdated--;
  50187. break;
  50188. case WorkerTaskType.COLLIDE:
  50189. var returnPayload = returnData.payload;
  50190. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  50191. return;
  50192. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  50193. if (callback) {
  50194. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  50195. if (mesh) {
  50196. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  50197. }
  50198. }
  50199. //cleanup
  50200. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  50201. break;
  50202. }
  50203. };
  50204. this._collisionsCallbackArray = [];
  50205. this._init = false;
  50206. this._runningUpdated = 0;
  50207. this._addUpdateMeshesList = {};
  50208. this._addUpdateGeometriesList = {};
  50209. this._toRemoveGeometryArray = [];
  50210. this._toRemoveMeshesArray = [];
  50211. }
  50212. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50213. if (!this._init)
  50214. return;
  50215. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  50216. return;
  50217. position.divideToRef(collider._radius, this._scaledPosition);
  50218. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50219. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  50220. var payload = {
  50221. collider: {
  50222. position: this._scaledPosition.asArray(),
  50223. velocity: this._scaledVelocity.asArray(),
  50224. radius: collider._radius.asArray()
  50225. },
  50226. collisionId: collisionIndex,
  50227. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  50228. maximumRetry: maximumRetry
  50229. };
  50230. var message = {
  50231. payload: payload,
  50232. taskType: WorkerTaskType.COLLIDE
  50233. };
  50234. this._worker.postMessage(message);
  50235. };
  50236. CollisionCoordinatorWorker.prototype.init = function (scene) {
  50237. this._scene = scene;
  50238. this._scene.registerAfterRender(this._afterRender);
  50239. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  50240. this._worker = new Worker(workerUrl);
  50241. this._worker.onmessage = this._onMessageFromWorker;
  50242. var message = {
  50243. payload: {},
  50244. taskType: WorkerTaskType.INIT
  50245. };
  50246. this._worker.postMessage(message);
  50247. };
  50248. CollisionCoordinatorWorker.prototype.destroy = function () {
  50249. this._scene.unregisterAfterRender(this._afterRender);
  50250. this._worker.terminate();
  50251. };
  50252. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  50253. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  50254. this.onMeshUpdated(mesh);
  50255. };
  50256. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  50257. this._toRemoveMeshesArray.push(mesh.uniqueId);
  50258. };
  50259. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  50260. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  50261. geometry.onGeometryUpdated = this.onGeometryUpdated;
  50262. this.onGeometryUpdated(geometry);
  50263. };
  50264. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  50265. this._toRemoveGeometryArray.push(geometry.id);
  50266. };
  50267. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  50268. var submeshes = [];
  50269. if (mesh.subMeshes) {
  50270. submeshes = mesh.subMeshes.map(function (sm, idx) {
  50271. var boundingInfo = sm.getBoundingInfo();
  50272. return {
  50273. position: idx,
  50274. verticesStart: sm.verticesStart,
  50275. verticesCount: sm.verticesCount,
  50276. indexStart: sm.indexStart,
  50277. indexCount: sm.indexCount,
  50278. hasMaterial: !!sm.getMaterial(),
  50279. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50280. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50281. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50282. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  50283. };
  50284. });
  50285. }
  50286. var geometryId = null;
  50287. if (mesh instanceof BABYLON.Mesh) {
  50288. var geometry = mesh.geometry;
  50289. geometryId = geometry ? geometry.id : null;
  50290. }
  50291. else if (mesh instanceof BABYLON.InstancedMesh) {
  50292. var geometry = mesh.sourceMesh.geometry;
  50293. geometryId = geometry ? geometry.id : null;
  50294. }
  50295. var boundingInfo = mesh.getBoundingInfo();
  50296. return {
  50297. uniqueId: mesh.uniqueId,
  50298. id: mesh.id,
  50299. name: mesh.name,
  50300. geometryId: geometryId,
  50301. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50302. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50303. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50304. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  50305. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  50306. subMeshes: submeshes,
  50307. checkCollisions: mesh.checkCollisions
  50308. };
  50309. };
  50310. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  50311. return {
  50312. id: geometry.id,
  50313. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  50314. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  50315. indices: new Uint32Array(geometry.getIndices() || []),
  50316. };
  50317. };
  50318. return CollisionCoordinatorWorker;
  50319. }());
  50320. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  50321. var CollisionCoordinatorLegacy = /** @class */ (function () {
  50322. function CollisionCoordinatorLegacy() {
  50323. this._scaledPosition = BABYLON.Vector3.Zero();
  50324. this._scaledVelocity = BABYLON.Vector3.Zero();
  50325. this._finalPosition = BABYLON.Vector3.Zero();
  50326. }
  50327. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50328. position.divideToRef(collider._radius, this._scaledPosition);
  50329. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50330. collider.collidedMesh = null;
  50331. collider._retry = 0;
  50332. collider._initialVelocity = this._scaledVelocity;
  50333. collider._initialPosition = this._scaledPosition;
  50334. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  50335. this._finalPosition.multiplyInPlace(collider._radius);
  50336. //run the callback
  50337. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  50338. };
  50339. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  50340. this._scene = scene;
  50341. };
  50342. CollisionCoordinatorLegacy.prototype.destroy = function () {
  50343. //Legacy need no destruction method.
  50344. };
  50345. //No update in legacy mode
  50346. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  50347. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  50348. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  50349. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  50350. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  50351. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  50352. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  50353. if (excludedMesh === void 0) { excludedMesh = null; }
  50354. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  50355. if (collider._retry >= maximumRetry) {
  50356. finalPosition.copyFrom(position);
  50357. return;
  50358. }
  50359. // Check if this is a mesh else camera or -1
  50360. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  50361. collider._initialize(position, velocity, closeDistance);
  50362. // Check all meshes
  50363. for (var index = 0; index < this._scene.meshes.length; index++) {
  50364. var mesh = this._scene.meshes[index];
  50365. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  50366. mesh._checkCollision(collider);
  50367. }
  50368. }
  50369. if (!collider.collisionFound) {
  50370. position.addToRef(velocity, finalPosition);
  50371. return;
  50372. }
  50373. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  50374. collider._getResponse(position, velocity);
  50375. }
  50376. if (velocity.length() <= closeDistance) {
  50377. finalPosition.copyFrom(position);
  50378. return;
  50379. }
  50380. collider._retry++;
  50381. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  50382. };
  50383. return CollisionCoordinatorLegacy;
  50384. }());
  50385. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  50386. })(BABYLON || (BABYLON = {}));
  50387. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  50388. var BABYLON;
  50389. (function (BABYLON) {
  50390. /**
  50391. * A particle represents one of the element emitted by a particle system.
  50392. * This is mainly define by its coordinates, direction, velocity and age.
  50393. */
  50394. var Particle = /** @class */ (function () {
  50395. /**
  50396. * Creates a new instance of @see Particle
  50397. * @param particleSystem the particle system the particle belongs to
  50398. */
  50399. function Particle(particleSystem) {
  50400. this.particleSystem = particleSystem;
  50401. /**
  50402. * The world position of the particle in the scene.
  50403. */
  50404. this.position = BABYLON.Vector3.Zero();
  50405. /**
  50406. * The world direction of the particle in the scene.
  50407. */
  50408. this.direction = BABYLON.Vector3.Zero();
  50409. /**
  50410. * The color of the particle.
  50411. */
  50412. this.color = new BABYLON.Color4(0, 0, 0, 0);
  50413. /**
  50414. * The color change of the particle per step.
  50415. */
  50416. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  50417. /**
  50418. * Defines how long will the life of the particle be.
  50419. */
  50420. this.lifeTime = 1.0;
  50421. /**
  50422. * The current age of the particle.
  50423. */
  50424. this.age = 0;
  50425. /**
  50426. * The current size of the particle.
  50427. */
  50428. this.size = 0;
  50429. /**
  50430. * The current angle of the particle.
  50431. */
  50432. this.angle = 0;
  50433. /**
  50434. * Defines how fast is the angle changing.
  50435. */
  50436. this.angularSpeed = 0;
  50437. /**
  50438. * Defines the cell index used by the particle to be rendered from a sprite.
  50439. */
  50440. this.cellIndex = 0;
  50441. this._currentFrameCounter = 0;
  50442. if (!this.particleSystem.isAnimationSheetEnabled) {
  50443. return;
  50444. }
  50445. this.cellIndex = this.particleSystem.startSpriteCellID;
  50446. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  50447. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  50448. }
  50449. else {
  50450. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  50451. }
  50452. }
  50453. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  50454. // (ageOffset / scaledUpdateSpeed) / available cells
  50455. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  50456. this._currentFrameCounter += scaledUpdateSpeed;
  50457. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  50458. this._currentFrameCounter = 0;
  50459. this.cellIndex++;
  50460. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50461. this.cellIndex = this.particleSystem.endSpriteCellID;
  50462. }
  50463. }
  50464. };
  50465. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  50466. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  50467. this.cellIndex++;
  50468. this._currentFrameCounter = 0;
  50469. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50470. if (this.particleSystem.spriteCellLoop) {
  50471. this.cellIndex = this.particleSystem.startSpriteCellID;
  50472. }
  50473. else {
  50474. this.cellIndex = this.particleSystem.endSpriteCellID;
  50475. }
  50476. }
  50477. }
  50478. else {
  50479. this._currentFrameCounter++;
  50480. }
  50481. };
  50482. /**
  50483. * Copy the properties of particle to another one.
  50484. * @param other the particle to copy the information to.
  50485. */
  50486. Particle.prototype.copyTo = function (other) {
  50487. other.position.copyFrom(this.position);
  50488. other.direction.copyFrom(this.direction);
  50489. other.color.copyFrom(this.color);
  50490. other.colorStep.copyFrom(this.colorStep);
  50491. other.lifeTime = this.lifeTime;
  50492. other.age = this.age;
  50493. other.size = this.size;
  50494. other.angle = this.angle;
  50495. other.angularSpeed = this.angularSpeed;
  50496. other.particleSystem = this.particleSystem;
  50497. other.cellIndex = this.cellIndex;
  50498. };
  50499. return Particle;
  50500. }());
  50501. BABYLON.Particle = Particle;
  50502. })(BABYLON || (BABYLON = {}));
  50503. //# sourceMappingURL=babylon.particle.js.map
  50504. var BABYLON;
  50505. (function (BABYLON) {
  50506. /**
  50507. * This represents a particle system in Babylon.
  50508. * 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.
  50509. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  50510. * @example https://doc.babylonjs.com/babylon101/particles
  50511. */
  50512. var ParticleSystem = /** @class */ (function () {
  50513. /**
  50514. * Instantiates a particle system.
  50515. * 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.
  50516. * @param name The name of the particle system
  50517. * @param capacity The max number of particles alive at the same time
  50518. * @param scene The scene the particle system belongs to
  50519. * @param customEffect a custom effect used to change the way particles are rendered by default
  50520. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  50521. * @param epsilon Offset used to render the particles
  50522. */
  50523. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  50524. if (customEffect === void 0) { customEffect = null; }
  50525. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  50526. if (epsilon === void 0) { epsilon = 0.01; }
  50527. var _this = this;
  50528. /**
  50529. * List of animations used by the particle system.
  50530. */
  50531. this.animations = [];
  50532. /**
  50533. * The rendering group used by the Particle system to chose when to render.
  50534. */
  50535. this.renderingGroupId = 0;
  50536. /**
  50537. * The emitter represents the Mesh or position we are attaching the particle system to.
  50538. */
  50539. this.emitter = null;
  50540. /**
  50541. * The maximum number of particles to emit per frame
  50542. */
  50543. this.emitRate = 10;
  50544. /**
  50545. * If you want to launch only a few particles at once, that can be done, as well.
  50546. */
  50547. this.manualEmitCount = -1;
  50548. /**
  50549. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  50550. */
  50551. this.updateSpeed = 0.01;
  50552. /**
  50553. * The amount of time the particle system is running (depends of the overall update speed).
  50554. */
  50555. this.targetStopDuration = 0;
  50556. /**
  50557. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  50558. */
  50559. this.disposeOnStop = false;
  50560. /**
  50561. * Minimum power of emitting particles.
  50562. */
  50563. this.minEmitPower = 1;
  50564. /**
  50565. * Maximum power of emitting particles.
  50566. */
  50567. this.maxEmitPower = 1;
  50568. /**
  50569. * Minimum life time of emitting particles.
  50570. */
  50571. this.minLifeTime = 1;
  50572. /**
  50573. * Maximum life time of emitting particles.
  50574. */
  50575. this.maxLifeTime = 1;
  50576. /**
  50577. * Minimum Size of emitting particles.
  50578. */
  50579. this.minSize = 1;
  50580. /**
  50581. * Maximum Size of emitting particles.
  50582. */
  50583. this.maxSize = 1;
  50584. /**
  50585. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  50586. */
  50587. this.minAngularSpeed = 0;
  50588. /**
  50589. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  50590. */
  50591. this.maxAngularSpeed = 0;
  50592. /**
  50593. * The layer mask we are rendering the particles through.
  50594. */
  50595. this.layerMask = 0x0FFFFFFF;
  50596. /**
  50597. * This can help using your own shader to render the particle system.
  50598. * The according effect will be created
  50599. */
  50600. this.customShader = null;
  50601. /**
  50602. * By default particle system starts as soon as they are created. This prevents the
  50603. * automatic start to happen and let you decide when to start emitting particles.
  50604. */
  50605. this.preventAutoStart = false;
  50606. /**
  50607. * Callback triggered when the particle animation is ending.
  50608. */
  50609. this.onAnimationEnd = null;
  50610. /**
  50611. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  50612. */
  50613. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  50614. /**
  50615. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  50616. * to override the particles.
  50617. */
  50618. this.forceDepthWrite = false;
  50619. /**
  50620. * You can use gravity if you want to give an orientation to your particles.
  50621. */
  50622. this.gravity = BABYLON.Vector3.Zero();
  50623. /**
  50624. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50625. */
  50626. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50627. /**
  50628. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50629. */
  50630. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50631. /**
  50632. * Color the particle will have at the end of its lifetime.
  50633. */
  50634. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  50635. /**
  50636. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  50637. */
  50638. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50639. /**
  50640. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  50641. */
  50642. this.spriteCellLoop = true;
  50643. /**
  50644. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  50645. */
  50646. this.spriteCellChangeSpeed = 0;
  50647. /**
  50648. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  50649. */
  50650. this.startSpriteCellID = 0;
  50651. /**
  50652. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  50653. */
  50654. this.endSpriteCellID = 0;
  50655. /**
  50656. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  50657. */
  50658. this.spriteCellWidth = 0;
  50659. /**
  50660. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  50661. */
  50662. this.spriteCellHeight = 0;
  50663. /**
  50664. * An event triggered when the system is disposed.
  50665. */
  50666. this.onDisposeObservable = new BABYLON.Observable();
  50667. this._particles = new Array();
  50668. this._stockParticles = new Array();
  50669. this._newPartsExcess = 0;
  50670. this._vertexBuffers = {};
  50671. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  50672. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  50673. this._scaledDirection = BABYLON.Vector3.Zero();
  50674. this._scaledGravity = BABYLON.Vector3.Zero();
  50675. this._currentRenderId = -1;
  50676. this._started = false;
  50677. this._stopped = false;
  50678. this._actualFrame = 0;
  50679. this._vertexBufferSize = 11;
  50680. this._appendParticleVertexes = null;
  50681. this.id = name;
  50682. this.name = name;
  50683. this._capacity = capacity;
  50684. this._epsilon = epsilon;
  50685. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  50686. if (isAnimationSheetEnabled) {
  50687. this._vertexBufferSize = 12;
  50688. }
  50689. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50690. this._customEffect = customEffect;
  50691. scene.particleSystems.push(this);
  50692. this._createIndexBuffer();
  50693. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  50694. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  50695. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  50696. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  50697. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  50698. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  50699. if (this._isAnimationSheetEnabled) {
  50700. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  50701. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  50702. }
  50703. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50704. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50705. this._vertexBuffers["options"] = options;
  50706. // Default emitter type
  50707. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  50708. this.updateFunction = function (particles) {
  50709. for (var index = 0; index < particles.length; index++) {
  50710. var particle = particles[index];
  50711. particle.age += _this._scaledUpdateSpeed;
  50712. if (particle.age >= particle.lifeTime) {
  50713. _this.recycleParticle(particle);
  50714. index--;
  50715. continue;
  50716. }
  50717. else {
  50718. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  50719. particle.color.addInPlace(_this._scaledColorStep);
  50720. if (particle.color.a < 0)
  50721. particle.color.a = 0;
  50722. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  50723. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  50724. particle.position.addInPlace(_this._scaledDirection);
  50725. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  50726. particle.direction.addInPlace(_this._scaledGravity);
  50727. if (_this._isAnimationSheetEnabled) {
  50728. particle.updateCellIndex(_this._scaledUpdateSpeed);
  50729. }
  50730. }
  50731. }
  50732. };
  50733. }
  50734. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  50735. /**
  50736. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50737. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50738. */
  50739. get: function () {
  50740. if (this.particleEmitterType.direction1) {
  50741. return this.particleEmitterType.direction1;
  50742. }
  50743. return BABYLON.Vector3.Zero();
  50744. },
  50745. set: function (value) {
  50746. if (this.particleEmitterType.direction1) {
  50747. this.particleEmitterType.direction1 = value;
  50748. }
  50749. },
  50750. enumerable: true,
  50751. configurable: true
  50752. });
  50753. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  50754. /**
  50755. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50756. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50757. */
  50758. get: function () {
  50759. if (this.particleEmitterType.direction2) {
  50760. return this.particleEmitterType.direction2;
  50761. }
  50762. return BABYLON.Vector3.Zero();
  50763. },
  50764. set: function (value) {
  50765. if (this.particleEmitterType.direction2) {
  50766. this.particleEmitterType.direction2 = value;
  50767. }
  50768. },
  50769. enumerable: true,
  50770. configurable: true
  50771. });
  50772. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  50773. /**
  50774. * 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.
  50775. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50776. */
  50777. get: function () {
  50778. if (this.particleEmitterType.minEmitBox) {
  50779. return this.particleEmitterType.minEmitBox;
  50780. }
  50781. return BABYLON.Vector3.Zero();
  50782. },
  50783. set: function (value) {
  50784. if (this.particleEmitterType.minEmitBox) {
  50785. this.particleEmitterType.minEmitBox = value;
  50786. }
  50787. },
  50788. enumerable: true,
  50789. configurable: true
  50790. });
  50791. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  50792. /**
  50793. * 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.
  50794. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50795. */
  50796. get: function () {
  50797. if (this.particleEmitterType.maxEmitBox) {
  50798. return this.particleEmitterType.maxEmitBox;
  50799. }
  50800. return BABYLON.Vector3.Zero();
  50801. },
  50802. set: function (value) {
  50803. if (this.particleEmitterType.maxEmitBox) {
  50804. this.particleEmitterType.maxEmitBox = value;
  50805. }
  50806. },
  50807. enumerable: true,
  50808. configurable: true
  50809. });
  50810. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  50811. /**
  50812. * Sets a callback that will be triggered when the system is disposed.
  50813. */
  50814. set: function (callback) {
  50815. if (this._onDisposeObserver) {
  50816. this.onDisposeObservable.remove(this._onDisposeObserver);
  50817. }
  50818. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50819. },
  50820. enumerable: true,
  50821. configurable: true
  50822. });
  50823. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  50824. /**
  50825. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  50826. */
  50827. get: function () {
  50828. return this._isAnimationSheetEnabled;
  50829. },
  50830. enumerable: true,
  50831. configurable: true
  50832. });
  50833. Object.defineProperty(ParticleSystem.prototype, "particles", {
  50834. /**
  50835. * Gets the current list of active particles
  50836. */
  50837. get: function () {
  50838. return this._particles;
  50839. },
  50840. enumerable: true,
  50841. configurable: true
  50842. });
  50843. /**
  50844. * Returns the string "ParticleSystem"
  50845. * @returns a string containing the class name
  50846. */
  50847. ParticleSystem.prototype.getClassName = function () {
  50848. return "ParticleSystem";
  50849. };
  50850. ParticleSystem.prototype._createIndexBuffer = function () {
  50851. var indices = [];
  50852. var index = 0;
  50853. for (var count = 0; count < this._capacity; count++) {
  50854. indices.push(index);
  50855. indices.push(index + 1);
  50856. indices.push(index + 2);
  50857. indices.push(index);
  50858. indices.push(index + 2);
  50859. indices.push(index + 3);
  50860. index += 4;
  50861. }
  50862. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  50863. };
  50864. /**
  50865. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  50866. * Its lifetime will start back at 0.
  50867. * @param particle The particle to recycle
  50868. */
  50869. ParticleSystem.prototype.recycleParticle = function (particle) {
  50870. var lastParticle = this._particles.pop();
  50871. if (lastParticle !== particle) {
  50872. lastParticle.copyTo(particle);
  50873. this._stockParticles.push(lastParticle);
  50874. }
  50875. };
  50876. /**
  50877. * Gets the maximum number of particles active at the same time.
  50878. * @returns The max number of active particles.
  50879. */
  50880. ParticleSystem.prototype.getCapacity = function () {
  50881. return this._capacity;
  50882. };
  50883. /**
  50884. * Gets Wether there are still active particles in the system.
  50885. * @returns True if it is alive, otherwise false.
  50886. */
  50887. ParticleSystem.prototype.isAlive = function () {
  50888. return this._alive;
  50889. };
  50890. /**
  50891. * Gets Wether the system has been started.
  50892. * @returns True if it has been started, otherwise false.
  50893. */
  50894. ParticleSystem.prototype.isStarted = function () {
  50895. return this._started;
  50896. };
  50897. /**
  50898. * Starts the particle system and begins to emit.
  50899. */
  50900. ParticleSystem.prototype.start = function () {
  50901. this._started = true;
  50902. this._stopped = false;
  50903. this._actualFrame = 0;
  50904. };
  50905. /**
  50906. * Stops the particle system.
  50907. */
  50908. ParticleSystem.prototype.stop = function () {
  50909. this._stopped = true;
  50910. };
  50911. /**
  50912. * Remove all active particles
  50913. */
  50914. ParticleSystem.prototype.reset = function () {
  50915. this._stockParticles = [];
  50916. this._particles = [];
  50917. };
  50918. /**
  50919. * @ignore (for internal use only)
  50920. */
  50921. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  50922. var offset = index * this._vertexBufferSize;
  50923. this._vertexData[offset] = particle.position.x;
  50924. this._vertexData[offset + 1] = particle.position.y;
  50925. this._vertexData[offset + 2] = particle.position.z;
  50926. this._vertexData[offset + 3] = particle.color.r;
  50927. this._vertexData[offset + 4] = particle.color.g;
  50928. this._vertexData[offset + 5] = particle.color.b;
  50929. this._vertexData[offset + 6] = particle.color.a;
  50930. this._vertexData[offset + 7] = particle.angle;
  50931. this._vertexData[offset + 8] = particle.size;
  50932. this._vertexData[offset + 9] = offsetX;
  50933. this._vertexData[offset + 10] = offsetY;
  50934. };
  50935. /**
  50936. * @ignore (for internal use only)
  50937. */
  50938. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  50939. if (offsetX === 0)
  50940. offsetX = this._epsilon;
  50941. else if (offsetX === 1)
  50942. offsetX = 1 - this._epsilon;
  50943. if (offsetY === 0)
  50944. offsetY = this._epsilon;
  50945. else if (offsetY === 1)
  50946. offsetY = 1 - this._epsilon;
  50947. var offset = index * this._vertexBufferSize;
  50948. this._vertexData[offset] = particle.position.x;
  50949. this._vertexData[offset + 1] = particle.position.y;
  50950. this._vertexData[offset + 2] = particle.position.z;
  50951. this._vertexData[offset + 3] = particle.color.r;
  50952. this._vertexData[offset + 4] = particle.color.g;
  50953. this._vertexData[offset + 5] = particle.color.b;
  50954. this._vertexData[offset + 6] = particle.color.a;
  50955. this._vertexData[offset + 7] = particle.angle;
  50956. this._vertexData[offset + 8] = particle.size;
  50957. this._vertexData[offset + 9] = offsetX;
  50958. this._vertexData[offset + 10] = offsetY;
  50959. this._vertexData[offset + 11] = particle.cellIndex;
  50960. };
  50961. ParticleSystem.prototype._update = function (newParticles) {
  50962. // Update current
  50963. this._alive = this._particles.length > 0;
  50964. this.updateFunction(this._particles);
  50965. // Add new ones
  50966. var worldMatrix;
  50967. if (this.emitter.position) {
  50968. var emitterMesh = this.emitter;
  50969. worldMatrix = emitterMesh.getWorldMatrix();
  50970. }
  50971. else {
  50972. var emitterPosition = this.emitter;
  50973. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  50974. }
  50975. var particle;
  50976. for (var index = 0; index < newParticles; index++) {
  50977. if (this._particles.length === this._capacity) {
  50978. break;
  50979. }
  50980. if (this._stockParticles.length !== 0) {
  50981. particle = this._stockParticles.pop();
  50982. particle.age = 0;
  50983. particle.cellIndex = this.startSpriteCellID;
  50984. }
  50985. else {
  50986. particle = new BABYLON.Particle(this);
  50987. }
  50988. this._particles.push(particle);
  50989. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  50990. if (this.startPositionFunction) {
  50991. this.startPositionFunction(worldMatrix, particle.position, particle);
  50992. }
  50993. else {
  50994. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  50995. }
  50996. if (this.startDirectionFunction) {
  50997. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  50998. }
  50999. else {
  51000. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51001. }
  51002. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  51003. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  51004. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  51005. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  51006. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  51007. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  51008. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  51009. }
  51010. };
  51011. ParticleSystem.prototype._getEffect = function () {
  51012. if (this._customEffect) {
  51013. return this._customEffect;
  51014. }
  51015. ;
  51016. var defines = [];
  51017. if (this._scene.clipPlane) {
  51018. defines.push("#define CLIPPLANE");
  51019. }
  51020. if (this._isAnimationSheetEnabled) {
  51021. defines.push("#define ANIMATESHEET");
  51022. }
  51023. // Effect
  51024. var join = defines.join("\n");
  51025. if (this._cachedDefines !== join) {
  51026. this._cachedDefines = join;
  51027. var attributesNamesOrOptions;
  51028. var effectCreationOption;
  51029. if (this._isAnimationSheetEnabled) {
  51030. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  51031. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  51032. }
  51033. else {
  51034. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  51035. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  51036. }
  51037. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  51038. }
  51039. return this._effect;
  51040. };
  51041. /**
  51042. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  51043. */
  51044. ParticleSystem.prototype.animate = function () {
  51045. if (!this._started)
  51046. return;
  51047. var effect = this._getEffect();
  51048. // Check
  51049. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  51050. return;
  51051. if (this._currentRenderId === this._scene.getRenderId()) {
  51052. return;
  51053. }
  51054. this._currentRenderId = this._scene.getRenderId();
  51055. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  51056. // determine the number of particles we need to create
  51057. var newParticles;
  51058. if (this.manualEmitCount > -1) {
  51059. newParticles = this.manualEmitCount;
  51060. this._newPartsExcess = 0;
  51061. this.manualEmitCount = 0;
  51062. }
  51063. else {
  51064. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  51065. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  51066. }
  51067. if (this._newPartsExcess > 1.0) {
  51068. newParticles += this._newPartsExcess >> 0;
  51069. this._newPartsExcess -= this._newPartsExcess >> 0;
  51070. }
  51071. this._alive = false;
  51072. if (!this._stopped) {
  51073. this._actualFrame += this._scaledUpdateSpeed;
  51074. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  51075. this.stop();
  51076. }
  51077. else {
  51078. newParticles = 0;
  51079. }
  51080. this._update(newParticles);
  51081. // Stopped?
  51082. if (this._stopped) {
  51083. if (!this._alive) {
  51084. this._started = false;
  51085. if (this.onAnimationEnd) {
  51086. this.onAnimationEnd();
  51087. }
  51088. if (this.disposeOnStop) {
  51089. this._scene._toBeDisposed.push(this);
  51090. }
  51091. }
  51092. }
  51093. // Animation sheet
  51094. if (this._isAnimationSheetEnabled) {
  51095. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  51096. }
  51097. else {
  51098. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  51099. }
  51100. // Update VBO
  51101. var offset = 0;
  51102. for (var index = 0; index < this._particles.length; index++) {
  51103. var particle = this._particles[index];
  51104. this._appendParticleVertexes(offset, particle);
  51105. offset += 4;
  51106. }
  51107. if (this._vertexBuffer) {
  51108. this._vertexBuffer.update(this._vertexData);
  51109. }
  51110. };
  51111. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  51112. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  51113. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  51114. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  51115. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  51116. };
  51117. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  51118. this._appendParticleVertex(offset++, particle, 0, 0);
  51119. this._appendParticleVertex(offset++, particle, 1, 0);
  51120. this._appendParticleVertex(offset++, particle, 1, 1);
  51121. this._appendParticleVertex(offset++, particle, 0, 1);
  51122. };
  51123. /**
  51124. * Rebuilds the particle system.
  51125. */
  51126. ParticleSystem.prototype.rebuild = function () {
  51127. this._createIndexBuffer();
  51128. if (this._vertexBuffer) {
  51129. this._vertexBuffer._rebuild();
  51130. }
  51131. };
  51132. /**
  51133. * Renders the particle system in its current state.
  51134. * @returns the current number of particles
  51135. */
  51136. ParticleSystem.prototype.render = function () {
  51137. var effect = this._getEffect();
  51138. // Check
  51139. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length) {
  51140. return 0;
  51141. }
  51142. var engine = this._scene.getEngine();
  51143. // Render
  51144. engine.enableEffect(effect);
  51145. engine.setState(false);
  51146. var viewMatrix = this._scene.getViewMatrix();
  51147. effect.setTexture("diffuseSampler", this.particleTexture);
  51148. effect.setMatrix("view", viewMatrix);
  51149. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  51150. if (this._isAnimationSheetEnabled) {
  51151. var baseSize = this.particleTexture.getBaseSize();
  51152. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  51153. }
  51154. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  51155. if (this._scene.clipPlane) {
  51156. var clipPlane = this._scene.clipPlane;
  51157. var invView = viewMatrix.clone();
  51158. invView.invert();
  51159. effect.setMatrix("invView", invView);
  51160. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  51161. }
  51162. // VBOs
  51163. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  51164. // Draw order
  51165. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  51166. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  51167. }
  51168. else {
  51169. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  51170. }
  51171. if (this.forceDepthWrite) {
  51172. engine.setDepthWrite(true);
  51173. }
  51174. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  51175. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  51176. return this._particles.length;
  51177. };
  51178. /**
  51179. * Disposes the particle system and free the associated resources
  51180. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  51181. */
  51182. ParticleSystem.prototype.dispose = function (disposeTexture) {
  51183. if (disposeTexture === void 0) { disposeTexture = true; }
  51184. if (this._vertexBuffer) {
  51185. this._vertexBuffer.dispose();
  51186. this._vertexBuffer = null;
  51187. }
  51188. if (this._indexBuffer) {
  51189. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  51190. this._indexBuffer = null;
  51191. }
  51192. if (disposeTexture && this.particleTexture) {
  51193. this.particleTexture.dispose();
  51194. this.particleTexture = null;
  51195. }
  51196. // Remove from scene
  51197. var index = this._scene.particleSystems.indexOf(this);
  51198. if (index > -1) {
  51199. this._scene.particleSystems.splice(index, 1);
  51200. }
  51201. // Callback
  51202. this.onDisposeObservable.notifyObservers(this);
  51203. this.onDisposeObservable.clear();
  51204. };
  51205. /**
  51206. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  51207. * @param radius The radius of the sphere to emit from
  51208. * @returns the emitter
  51209. */
  51210. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  51211. if (radius === void 0) { radius = 1; }
  51212. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  51213. this.particleEmitterType = particleEmitter;
  51214. return particleEmitter;
  51215. };
  51216. /**
  51217. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  51218. * @param radius The radius of the sphere to emit from
  51219. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  51220. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  51221. * @returns the emitter
  51222. */
  51223. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  51224. if (radius === void 0) { radius = 1; }
  51225. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  51226. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  51227. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  51228. this.particleEmitterType = particleEmitter;
  51229. return particleEmitter;
  51230. };
  51231. /**
  51232. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  51233. * @param radius The radius of the cone to emit from
  51234. * @param angle The base angle of the cone
  51235. * @returns the emitter
  51236. */
  51237. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  51238. if (radius === void 0) { radius = 1; }
  51239. if (angle === void 0) { angle = Math.PI / 4; }
  51240. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  51241. this.particleEmitterType = particleEmitter;
  51242. return particleEmitter;
  51243. };
  51244. // 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.
  51245. /**
  51246. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  51247. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  51248. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  51249. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51250. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51251. * @returns the emitter
  51252. */
  51253. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  51254. var particleEmitter = new BABYLON.BoxParticleEmitter();
  51255. this.direction1 = direction1;
  51256. this.direction2 = direction2;
  51257. this.minEmitBox = minEmitBox;
  51258. this.maxEmitBox = maxEmitBox;
  51259. this.particleEmitterType = particleEmitter;
  51260. return particleEmitter;
  51261. };
  51262. /**
  51263. * Clones the particle system.
  51264. * @param name The name of the cloned object
  51265. * @param newEmitter The new emitter to use
  51266. * @returns the cloned particle system
  51267. */
  51268. ParticleSystem.prototype.clone = function (name, newEmitter) {
  51269. var custom = null;
  51270. var program = null;
  51271. if (this.customShader != null) {
  51272. program = this.customShader;
  51273. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51274. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51275. }
  51276. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  51277. result.customShader = program;
  51278. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  51279. if (newEmitter === undefined) {
  51280. newEmitter = this.emitter;
  51281. }
  51282. result.emitter = newEmitter;
  51283. if (this.particleTexture) {
  51284. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  51285. }
  51286. if (!this.preventAutoStart) {
  51287. result.start();
  51288. }
  51289. return result;
  51290. };
  51291. /**
  51292. * Serializes the particle system to a JSON object.
  51293. * @returns the JSON object
  51294. */
  51295. ParticleSystem.prototype.serialize = function () {
  51296. var serializationObject = {};
  51297. serializationObject.name = this.name;
  51298. serializationObject.id = this.id;
  51299. // Emitter
  51300. if (this.emitter.position) {
  51301. var emitterMesh = this.emitter;
  51302. serializationObject.emitterId = emitterMesh.id;
  51303. }
  51304. else {
  51305. var emitterPosition = this.emitter;
  51306. serializationObject.emitter = emitterPosition.asArray();
  51307. }
  51308. serializationObject.capacity = this.getCapacity();
  51309. if (this.particleTexture) {
  51310. serializationObject.textureName = this.particleTexture.name;
  51311. }
  51312. // Animations
  51313. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  51314. // Particle system
  51315. serializationObject.minAngularSpeed = this.minAngularSpeed;
  51316. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  51317. serializationObject.minSize = this.minSize;
  51318. serializationObject.maxSize = this.maxSize;
  51319. serializationObject.minEmitPower = this.minEmitPower;
  51320. serializationObject.maxEmitPower = this.maxEmitPower;
  51321. serializationObject.minLifeTime = this.minLifeTime;
  51322. serializationObject.maxLifeTime = this.maxLifeTime;
  51323. serializationObject.emitRate = this.emitRate;
  51324. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51325. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51326. serializationObject.gravity = this.gravity.asArray();
  51327. serializationObject.direction1 = this.direction1.asArray();
  51328. serializationObject.direction2 = this.direction2.asArray();
  51329. serializationObject.color1 = this.color1.asArray();
  51330. serializationObject.color2 = this.color2.asArray();
  51331. serializationObject.colorDead = this.colorDead.asArray();
  51332. serializationObject.updateSpeed = this.updateSpeed;
  51333. serializationObject.targetStopDuration = this.targetStopDuration;
  51334. serializationObject.textureMask = this.textureMask.asArray();
  51335. serializationObject.blendMode = this.blendMode;
  51336. serializationObject.customShader = this.customShader;
  51337. serializationObject.preventAutoStart = this.preventAutoStart;
  51338. serializationObject.startSpriteCellID = this.startSpriteCellID;
  51339. serializationObject.endSpriteCellID = this.endSpriteCellID;
  51340. serializationObject.spriteCellLoop = this.spriteCellLoop;
  51341. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  51342. serializationObject.spriteCellWidth = this.spriteCellWidth;
  51343. serializationObject.spriteCellHeight = this.spriteCellHeight;
  51344. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  51345. // Emitter
  51346. if (this.particleEmitterType) {
  51347. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  51348. }
  51349. return serializationObject;
  51350. };
  51351. /**
  51352. * Parses a JSON object to create a particle system.
  51353. * @param parsedParticleSystem The JSON object to parse
  51354. * @param scene The scene to create the particle system in
  51355. * @param rootUrl The root url to use to load external dependencies like texture
  51356. * @returns the Parsed particle system
  51357. */
  51358. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  51359. var name = parsedParticleSystem.name;
  51360. var custom = null;
  51361. var program = null;
  51362. if (parsedParticleSystem.customShader) {
  51363. program = parsedParticleSystem.customShader;
  51364. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51365. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51366. }
  51367. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  51368. particleSystem.customShader = program;
  51369. if (parsedParticleSystem.id) {
  51370. particleSystem.id = parsedParticleSystem.id;
  51371. }
  51372. // Auto start
  51373. if (parsedParticleSystem.preventAutoStart) {
  51374. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  51375. }
  51376. // Texture
  51377. if (parsedParticleSystem.textureName) {
  51378. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  51379. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  51380. }
  51381. // Emitter
  51382. if (parsedParticleSystem.emitterId) {
  51383. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  51384. }
  51385. else {
  51386. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  51387. }
  51388. // Animations
  51389. if (parsedParticleSystem.animations) {
  51390. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  51391. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  51392. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  51393. }
  51394. }
  51395. if (parsedParticleSystem.autoAnimate) {
  51396. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  51397. }
  51398. // Particle system
  51399. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  51400. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  51401. particleSystem.minSize = parsedParticleSystem.minSize;
  51402. particleSystem.maxSize = parsedParticleSystem.maxSize;
  51403. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  51404. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  51405. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  51406. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  51407. particleSystem.emitRate = parsedParticleSystem.emitRate;
  51408. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  51409. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  51410. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  51411. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  51412. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  51413. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  51414. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  51415. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  51416. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  51417. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  51418. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  51419. particleSystem.blendMode = parsedParticleSystem.blendMode;
  51420. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  51421. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  51422. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  51423. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  51424. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  51425. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  51426. if (!particleSystem.preventAutoStart) {
  51427. particleSystem.start();
  51428. }
  51429. return particleSystem;
  51430. };
  51431. /**
  51432. * Source color is added to the destination color without alpha affecting the result.
  51433. */
  51434. ParticleSystem.BLENDMODE_ONEONE = 0;
  51435. /**
  51436. * Blend current color and particle color using particle’s alpha.
  51437. */
  51438. ParticleSystem.BLENDMODE_STANDARD = 1;
  51439. return ParticleSystem;
  51440. }());
  51441. BABYLON.ParticleSystem = ParticleSystem;
  51442. })(BABYLON || (BABYLON = {}));
  51443. //# sourceMappingURL=babylon.particleSystem.js.map
  51444. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  51445. var BABYLON;
  51446. (function (BABYLON) {
  51447. /**
  51448. * Particle emitter emitting particles from the inside of a box.
  51449. * It emits the particles randomly between 2 given directions.
  51450. */
  51451. var BoxParticleEmitter = /** @class */ (function () {
  51452. /**
  51453. * Creates a new instance of @see BoxParticleEmitter
  51454. */
  51455. function BoxParticleEmitter() {
  51456. /**
  51457. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51458. */
  51459. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  51460. /**
  51461. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51462. */
  51463. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  51464. /**
  51465. * 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.
  51466. */
  51467. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  51468. /**
  51469. * 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.
  51470. */
  51471. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  51472. }
  51473. /**
  51474. * Called by the particle System when the direction is computed for the created particle.
  51475. * @param emitPower is the power of the particle (speed)
  51476. * @param worldMatrix is the world matrix of the particle system
  51477. * @param directionToUpdate is the direction vector to update with the result
  51478. * @param particle is the particle we are computed the direction for
  51479. */
  51480. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51481. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51482. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51483. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51484. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51485. };
  51486. /**
  51487. * Called by the particle System when the position is computed for the created particle.
  51488. * @param worldMatrix is the world matrix of the particle system
  51489. * @param positionToUpdate is the position vector to update with the result
  51490. * @param particle is the particle we are computed the position for
  51491. */
  51492. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51493. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  51494. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  51495. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  51496. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51497. };
  51498. /**
  51499. * Clones the current emitter and returns a copy of it
  51500. * @returns the new emitter
  51501. */
  51502. BoxParticleEmitter.prototype.clone = function () {
  51503. var newOne = new BoxParticleEmitter();
  51504. BABYLON.Tools.DeepCopy(this, newOne);
  51505. return newOne;
  51506. };
  51507. /**
  51508. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51509. * @param effect defines the update shader
  51510. */
  51511. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  51512. effect.setVector3("direction1", this.direction1);
  51513. effect.setVector3("direction2", this.direction2);
  51514. effect.setVector3("minEmitBox", this.minEmitBox);
  51515. effect.setVector3("maxEmitBox", this.maxEmitBox);
  51516. };
  51517. /**
  51518. * Returns a string to use to update the GPU particles update shader
  51519. * @returns a string containng the defines string
  51520. */
  51521. BoxParticleEmitter.prototype.getEffectDefines = function () {
  51522. return "#define BOXEMITTER";
  51523. };
  51524. /**
  51525. * Returns the string "BoxEmitter"
  51526. * @returns a string containing the class name
  51527. */
  51528. BoxParticleEmitter.prototype.getClassName = function () {
  51529. return "BoxEmitter";
  51530. };
  51531. /**
  51532. * Serializes the particle system to a JSON object.
  51533. * @returns the JSON object
  51534. */
  51535. BoxParticleEmitter.prototype.serialize = function () {
  51536. var serializationObject = {};
  51537. serializationObject.type = this.getClassName();
  51538. serializationObject.direction1 = this.direction1.asArray();
  51539. ;
  51540. serializationObject.direction2 = this.direction2.asArray();
  51541. ;
  51542. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51543. ;
  51544. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51545. ;
  51546. return serializationObject;
  51547. };
  51548. /**
  51549. * Parse properties from a JSON object
  51550. * @param serializationObject defines the JSON object
  51551. */
  51552. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  51553. this.direction1.copyFrom(serializationObject.direction1);
  51554. this.direction2.copyFrom(serializationObject.direction2);
  51555. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  51556. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  51557. };
  51558. return BoxParticleEmitter;
  51559. }());
  51560. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  51561. })(BABYLON || (BABYLON = {}));
  51562. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  51563. var BABYLON;
  51564. (function (BABYLON) {
  51565. /**
  51566. * Particle emitter emitting particles from the inside of a cone.
  51567. * It emits the particles alongside the cone volume from the base to the particle.
  51568. * The emission direction might be randomized.
  51569. */
  51570. var ConeParticleEmitter = /** @class */ (function () {
  51571. /**
  51572. * Creates a new instance of @see ConeParticleEmitter
  51573. * @param radius the radius of the emission cone (1 by default)
  51574. * @param angles the cone base angle (PI by default)
  51575. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51576. */
  51577. function ConeParticleEmitter(radius,
  51578. /**
  51579. * The radius of the emission cone.
  51580. */
  51581. angle,
  51582. /**
  51583. * The cone base angle.
  51584. */
  51585. directionRandomizer) {
  51586. if (radius === void 0) { radius = 1; }
  51587. if (angle === void 0) { angle = Math.PI; }
  51588. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51589. this.angle = angle;
  51590. this.directionRandomizer = directionRandomizer;
  51591. this.radius = radius;
  51592. }
  51593. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  51594. /**
  51595. * Gets the radius of the emission cone.
  51596. */
  51597. get: function () {
  51598. return this._radius;
  51599. },
  51600. /**
  51601. * Sets the radius of the emission cone.
  51602. */
  51603. set: function (value) {
  51604. this._radius = value;
  51605. if (this.angle !== 0) {
  51606. this._height = value / Math.tan(this.angle / 2);
  51607. }
  51608. else {
  51609. this._height = 1;
  51610. }
  51611. },
  51612. enumerable: true,
  51613. configurable: true
  51614. });
  51615. /**
  51616. * Called by the particle System when the direction is computed for the created particle.
  51617. * @param emitPower is the power of the particle (speed)
  51618. * @param worldMatrix is the world matrix of the particle system
  51619. * @param directionToUpdate is the direction vector to update with the result
  51620. * @param particle is the particle we are computed the direction for
  51621. */
  51622. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51623. if (this.angle === 0) {
  51624. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  51625. }
  51626. else {
  51627. // measure the direction Vector from the emitter to the particle.
  51628. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51629. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51630. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51631. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51632. direction.x += randX;
  51633. direction.y += randY;
  51634. direction.z += randZ;
  51635. direction.normalize();
  51636. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51637. }
  51638. };
  51639. /**
  51640. * Called by the particle System when the position is computed for the created particle.
  51641. * @param worldMatrix is the world matrix of the particle system
  51642. * @param positionToUpdate is the position vector to update with the result
  51643. * @param particle is the particle we are computed the position for
  51644. */
  51645. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51646. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  51647. var h = BABYLON.Scalar.RandomRange(0, 1);
  51648. // Better distribution in a cone at normal angles.
  51649. h = 1 - h * h;
  51650. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  51651. radius = radius * h / this._height;
  51652. var randX = radius * Math.sin(s);
  51653. var randZ = radius * Math.cos(s);
  51654. var randY = h * this._height;
  51655. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51656. };
  51657. /**
  51658. * Clones the current emitter and returns a copy of it
  51659. * @returns the new emitter
  51660. */
  51661. ConeParticleEmitter.prototype.clone = function () {
  51662. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  51663. BABYLON.Tools.DeepCopy(this, newOne);
  51664. return newOne;
  51665. };
  51666. /**
  51667. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51668. * @param effect defines the update shader
  51669. */
  51670. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  51671. effect.setFloat("radius", this.radius);
  51672. effect.setFloat("angle", this.angle);
  51673. effect.setFloat("height", this._height);
  51674. effect.setFloat("directionRandomizer", this.directionRandomizer);
  51675. };
  51676. /**
  51677. * Returns a string to use to update the GPU particles update shader
  51678. * @returns a string containng the defines string
  51679. */
  51680. ConeParticleEmitter.prototype.getEffectDefines = function () {
  51681. return "#define CONEEMITTER";
  51682. };
  51683. /**
  51684. * Returns the string "BoxEmitter"
  51685. * @returns a string containing the class name
  51686. */
  51687. ConeParticleEmitter.prototype.getClassName = function () {
  51688. return "ConeEmitter";
  51689. };
  51690. /**
  51691. * Serializes the particle system to a JSON object.
  51692. * @returns the JSON object
  51693. */
  51694. ConeParticleEmitter.prototype.serialize = function () {
  51695. var serializationObject = {};
  51696. serializationObject.type = this.getClassName();
  51697. serializationObject.radius = this.radius;
  51698. serializationObject.angle = this.angle;
  51699. serializationObject.directionRandomizer = this.directionRandomizer;
  51700. return serializationObject;
  51701. };
  51702. /**
  51703. * Parse properties from a JSON object
  51704. * @param serializationObject defines the JSON object
  51705. */
  51706. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  51707. this.radius = serializationObject.radius;
  51708. this.angle = serializationObject.angle;
  51709. this.directionRandomizer = serializationObject.directionRandomizer;
  51710. };
  51711. return ConeParticleEmitter;
  51712. }());
  51713. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  51714. })(BABYLON || (BABYLON = {}));
  51715. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  51716. var BABYLON;
  51717. (function (BABYLON) {
  51718. /**
  51719. * Particle emitter emitting particles from the inside of a sphere.
  51720. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  51721. */
  51722. var SphereParticleEmitter = /** @class */ (function () {
  51723. /**
  51724. * Creates a new instance of @see SphereParticleEmitter
  51725. * @param radius the radius of the emission sphere (1 by default)
  51726. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51727. */
  51728. function SphereParticleEmitter(
  51729. /**
  51730. * The radius of the emission sphere.
  51731. */
  51732. radius,
  51733. /**
  51734. * How much to randomize the particle direction [0-1].
  51735. */
  51736. directionRandomizer) {
  51737. if (radius === void 0) { radius = 1; }
  51738. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51739. this.radius = radius;
  51740. this.directionRandomizer = directionRandomizer;
  51741. }
  51742. /**
  51743. * Called by the particle System when the direction is computed for the created particle.
  51744. * @param emitPower is the power of the particle (speed)
  51745. * @param worldMatrix is the world matrix of the particle system
  51746. * @param directionToUpdate is the direction vector to update with the result
  51747. * @param particle is the particle we are computed the direction for
  51748. */
  51749. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51750. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51751. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51752. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51753. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51754. direction.x += randX;
  51755. direction.y += randY;
  51756. direction.z += randZ;
  51757. direction.normalize();
  51758. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51759. };
  51760. /**
  51761. * Called by the particle System when the position is computed for the created particle.
  51762. * @param worldMatrix is the world matrix of the particle system
  51763. * @param positionToUpdate is the position vector to update with the result
  51764. * @param particle is the particle we are computed the position for
  51765. */
  51766. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51767. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  51768. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  51769. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  51770. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  51771. var randY = randRadius * Math.cos(theta);
  51772. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  51773. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51774. };
  51775. /**
  51776. * Clones the current emitter and returns a copy of it
  51777. * @returns the new emitter
  51778. */
  51779. SphereParticleEmitter.prototype.clone = function () {
  51780. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  51781. BABYLON.Tools.DeepCopy(this, newOne);
  51782. return newOne;
  51783. };
  51784. /**
  51785. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51786. * @param effect defines the update shader
  51787. */
  51788. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  51789. effect.setFloat("radius", this.radius);
  51790. effect.setFloat("directionRandomizer", this.directionRandomizer);
  51791. };
  51792. /**
  51793. * Returns a string to use to update the GPU particles update shader
  51794. * @returns a string containng the defines string
  51795. */
  51796. SphereParticleEmitter.prototype.getEffectDefines = function () {
  51797. return "#define SPHEREEMITTER";
  51798. };
  51799. /**
  51800. * Returns the string "SphereParticleEmitter"
  51801. * @returns a string containing the class name
  51802. */
  51803. SphereParticleEmitter.prototype.getClassName = function () {
  51804. return "SphereParticleEmitter";
  51805. };
  51806. /**
  51807. * Serializes the particle system to a JSON object.
  51808. * @returns the JSON object
  51809. */
  51810. SphereParticleEmitter.prototype.serialize = function () {
  51811. var serializationObject = {};
  51812. serializationObject.type = this.getClassName();
  51813. serializationObject.radius = this.radius;
  51814. serializationObject.directionRandomizer = this.directionRandomizer;
  51815. return serializationObject;
  51816. };
  51817. /**
  51818. * Parse properties from a JSON object
  51819. * @param serializationObject defines the JSON object
  51820. */
  51821. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  51822. this.radius = serializationObject.radius;
  51823. this.directionRandomizer = serializationObject.directionRandomizer;
  51824. };
  51825. return SphereParticleEmitter;
  51826. }());
  51827. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  51828. /**
  51829. * Particle emitter emitting particles from the inside of a sphere.
  51830. * It emits the particles randomly between two vectors.
  51831. */
  51832. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  51833. __extends(SphereDirectedParticleEmitter, _super);
  51834. /**
  51835. * Creates a new instance of @see SphereDirectedParticleEmitter
  51836. * @param radius the radius of the emission sphere (1 by default)
  51837. * @param direction1 the min limit of the emission direction (up vector by default)
  51838. * @param direction2 the max limit of the emission direction (up vector by default)
  51839. */
  51840. function SphereDirectedParticleEmitter(radius,
  51841. /**
  51842. * The min limit of the emission direction.
  51843. */
  51844. direction1,
  51845. /**
  51846. * The max limit of the emission direction.
  51847. */
  51848. direction2) {
  51849. if (radius === void 0) { radius = 1; }
  51850. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  51851. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  51852. var _this = _super.call(this, radius) || this;
  51853. _this.direction1 = direction1;
  51854. _this.direction2 = direction2;
  51855. return _this;
  51856. }
  51857. /**
  51858. * Called by the particle System when the direction is computed for the created particle.
  51859. * @param emitPower is the power of the particle (speed)
  51860. * @param worldMatrix is the world matrix of the particle system
  51861. * @param directionToUpdate is the direction vector to update with the result
  51862. * @param particle is the particle we are computed the direction for
  51863. */
  51864. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51865. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51866. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51867. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51868. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51869. };
  51870. /**
  51871. * Clones the current emitter and returns a copy of it
  51872. * @returns the new emitter
  51873. */
  51874. SphereDirectedParticleEmitter.prototype.clone = function () {
  51875. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  51876. BABYLON.Tools.DeepCopy(this, newOne);
  51877. return newOne;
  51878. };
  51879. /**
  51880. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51881. * @param effect defines the update shader
  51882. */
  51883. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  51884. effect.setFloat("radius", this.radius);
  51885. effect.setVector3("direction1", this.direction1);
  51886. effect.setVector3("direction2", this.direction2);
  51887. };
  51888. /**
  51889. * Returns a string to use to update the GPU particles update shader
  51890. * @returns a string containng the defines string
  51891. */
  51892. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  51893. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  51894. };
  51895. /**
  51896. * Returns the string "SphereDirectedParticleEmitter"
  51897. * @returns a string containing the class name
  51898. */
  51899. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  51900. return "SphereDirectedParticleEmitter";
  51901. };
  51902. /**
  51903. * Serializes the particle system to a JSON object.
  51904. * @returns the JSON object
  51905. */
  51906. SphereDirectedParticleEmitter.prototype.serialize = function () {
  51907. var serializationObject = _super.prototype.serialize.call(this);
  51908. ;
  51909. serializationObject.direction1 = this.direction1.asArray();
  51910. ;
  51911. serializationObject.direction2 = this.direction2.asArray();
  51912. ;
  51913. return serializationObject;
  51914. };
  51915. /**
  51916. * Parse properties from a JSON object
  51917. * @param serializationObject defines the JSON object
  51918. */
  51919. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  51920. _super.prototype.parse.call(this, serializationObject);
  51921. this.direction1.copyFrom(serializationObject.direction1);
  51922. this.direction2.copyFrom(serializationObject.direction2);
  51923. };
  51924. return SphereDirectedParticleEmitter;
  51925. }(SphereParticleEmitter));
  51926. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  51927. })(BABYLON || (BABYLON = {}));
  51928. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  51929. var __assign = (this && this.__assign) || Object.assign || function(t) {
  51930. for (var s, i = 1, n = arguments.length; i < n; i++) {
  51931. s = arguments[i];
  51932. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  51933. t[p] = s[p];
  51934. }
  51935. return t;
  51936. };
  51937. var BABYLON;
  51938. (function (BABYLON) {
  51939. /**
  51940. * This represents a GPU particle system in Babylon
  51941. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  51942. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  51943. */
  51944. var GPUParticleSystem = /** @class */ (function () {
  51945. /**
  51946. * Instantiates a GPU particle system.
  51947. * 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.
  51948. * @param name The name of the particle system
  51949. * @param capacity The max number of particles alive at the same time
  51950. * @param scene The scene the particle system belongs to
  51951. */
  51952. function GPUParticleSystem(name, options, scene) {
  51953. /**
  51954. * The emitter represents the Mesh or position we are attaching the particle system to.
  51955. */
  51956. this.emitter = null;
  51957. /**
  51958. * The rendering group used by the Particle system to chose when to render.
  51959. */
  51960. this.renderingGroupId = 0;
  51961. /**
  51962. * The layer mask we are rendering the particles through.
  51963. */
  51964. this.layerMask = 0x0FFFFFFF;
  51965. this._targetIndex = 0;
  51966. this._currentRenderId = -1;
  51967. this._started = false;
  51968. this._stopped = false;
  51969. this._timeDelta = 0;
  51970. this._attributesStrideSize = 14;
  51971. this._actualFrame = 0;
  51972. /**
  51973. * List of animations used by the particle system.
  51974. */
  51975. this.animations = [];
  51976. /**
  51977. * An event triggered when the system is disposed.
  51978. */
  51979. this.onDisposeObservable = new BABYLON.Observable();
  51980. /**
  51981. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  51982. */
  51983. this.updateSpeed = 0.01;
  51984. /**
  51985. * The amount of time the particle system is running (depends of the overall update speed).
  51986. */
  51987. this.targetStopDuration = 0;
  51988. /**
  51989. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  51990. */
  51991. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  51992. /**
  51993. * Minimum life time of emitting particles.
  51994. */
  51995. this.minLifeTime = 1;
  51996. /**
  51997. * Maximum life time of emitting particles.
  51998. */
  51999. this.maxLifeTime = 1;
  52000. /**
  52001. * Minimum Size of emitting particles.
  52002. */
  52003. this.minSize = 1;
  52004. /**
  52005. * Maximum Size of emitting particles.
  52006. */
  52007. this.maxSize = 1;
  52008. /**
  52009. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  52010. */
  52011. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52012. /**
  52013. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  52014. */
  52015. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52016. /**
  52017. * Color the particle will have at the end of its lifetime.
  52018. */
  52019. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  52020. /**
  52021. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  52022. */
  52023. this.emitRate = 100;
  52024. /**
  52025. * You can use gravity if you want to give an orientation to your particles.
  52026. */
  52027. this.gravity = BABYLON.Vector3.Zero();
  52028. /**
  52029. * Minimum power of emitting particles.
  52030. */
  52031. this.minEmitPower = 1;
  52032. /**
  52033. * Maximum power of emitting particles.
  52034. */
  52035. this.maxEmitPower = 1;
  52036. this.id = name;
  52037. this.name = name;
  52038. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52039. this._engine = this._scene.getEngine();
  52040. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  52041. this._capacity = fullOptions.capacity;
  52042. this._activeCount = fullOptions.capacity;
  52043. this._currentActiveCount = 0;
  52044. this._scene.particleSystems.push(this);
  52045. this._updateEffectOptions = {
  52046. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  52047. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  52048. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle"],
  52049. uniformBuffersNames: [],
  52050. samplers: ["randomSampler"],
  52051. defines: "",
  52052. fallbacks: null,
  52053. onCompiled: null,
  52054. onError: null,
  52055. indexParameters: null,
  52056. maxSimultaneousLights: 0,
  52057. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  52058. };
  52059. // Random data
  52060. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  52061. var d = [];
  52062. for (var i = 0; i < maxTextureSize; ++i) {
  52063. d.push(Math.random());
  52064. d.push(Math.random());
  52065. d.push(Math.random());
  52066. d.push(Math.random());
  52067. }
  52068. 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);
  52069. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52070. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52071. this._randomTextureSize = maxTextureSize;
  52072. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  52073. }
  52074. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  52075. /**
  52076. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  52077. */
  52078. get: function () {
  52079. if (!BABYLON.Engine.LastCreatedEngine) {
  52080. return false;
  52081. }
  52082. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  52083. },
  52084. enumerable: true,
  52085. configurable: true
  52086. });
  52087. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  52088. /**
  52089. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52090. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52091. */
  52092. get: function () {
  52093. if (this.particleEmitterType.direction1) {
  52094. return this.particleEmitterType.direction1;
  52095. }
  52096. return BABYLON.Vector3.Zero();
  52097. },
  52098. set: function (value) {
  52099. if (this.particleEmitterType.direction1) {
  52100. this.particleEmitterType.direction1 = value;
  52101. }
  52102. },
  52103. enumerable: true,
  52104. configurable: true
  52105. });
  52106. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  52107. /**
  52108. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52109. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52110. */
  52111. get: function () {
  52112. if (this.particleEmitterType.direction2) {
  52113. return this.particleEmitterType.direction2;
  52114. }
  52115. return BABYLON.Vector3.Zero();
  52116. },
  52117. set: function (value) {
  52118. if (this.particleEmitterType.direction2) {
  52119. this.particleEmitterType.direction2 = value;
  52120. }
  52121. },
  52122. enumerable: true,
  52123. configurable: true
  52124. });
  52125. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  52126. /**
  52127. * 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.
  52128. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52129. */
  52130. get: function () {
  52131. if (this.particleEmitterType.minEmitBox) {
  52132. return this.particleEmitterType.minEmitBox;
  52133. }
  52134. return BABYLON.Vector3.Zero();
  52135. },
  52136. set: function (value) {
  52137. if (this.particleEmitterType.minEmitBox) {
  52138. this.particleEmitterType.minEmitBox = value;
  52139. }
  52140. },
  52141. enumerable: true,
  52142. configurable: true
  52143. });
  52144. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  52145. /**
  52146. * 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.
  52147. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52148. */
  52149. get: function () {
  52150. if (this.particleEmitterType.maxEmitBox) {
  52151. return this.particleEmitterType.maxEmitBox;
  52152. }
  52153. return BABYLON.Vector3.Zero();
  52154. },
  52155. set: function (value) {
  52156. if (this.particleEmitterType.maxEmitBox) {
  52157. this.particleEmitterType.maxEmitBox = value;
  52158. }
  52159. },
  52160. enumerable: true,
  52161. configurable: true
  52162. });
  52163. /**
  52164. * Gets the maximum number of particles active at the same time.
  52165. * @returns The max number of active particles.
  52166. */
  52167. GPUParticleSystem.prototype.getCapacity = function () {
  52168. return this._capacity;
  52169. };
  52170. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  52171. /**
  52172. * Gets or set the number of active particles
  52173. */
  52174. get: function () {
  52175. return this._activeCount;
  52176. },
  52177. set: function (value) {
  52178. this._activeCount = Math.min(value, this._capacity);
  52179. },
  52180. enumerable: true,
  52181. configurable: true
  52182. });
  52183. /**
  52184. * Gets Wether the system has been started.
  52185. * @returns True if it has been started, otherwise false.
  52186. */
  52187. GPUParticleSystem.prototype.isStarted = function () {
  52188. return this._started;
  52189. };
  52190. /**
  52191. * Starts the particle system and begins to emit.
  52192. */
  52193. GPUParticleSystem.prototype.start = function () {
  52194. this._started = true;
  52195. this._stopped = false;
  52196. };
  52197. /**
  52198. * Stops the particle system.
  52199. */
  52200. GPUParticleSystem.prototype.stop = function () {
  52201. this._stopped = true;
  52202. };
  52203. /**
  52204. * Remove all active particles
  52205. */
  52206. GPUParticleSystem.prototype.reset = function () {
  52207. this._releaseBuffers();
  52208. this._releaseVAOs();
  52209. this._currentActiveCount = 0;
  52210. this._targetIndex = 0;
  52211. };
  52212. /**
  52213. * Returns the string "GPUParticleSystem"
  52214. * @returns a string containing the class name
  52215. */
  52216. GPUParticleSystem.prototype.getClassName = function () {
  52217. return "GPUParticleSystem";
  52218. };
  52219. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  52220. var updateVertexBuffers = {};
  52221. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  52222. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  52223. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  52224. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  52225. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  52226. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  52227. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  52228. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  52229. this._engine.bindArrayBuffer(null);
  52230. return vao;
  52231. };
  52232. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  52233. var renderVertexBuffers = {};
  52234. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  52235. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  52236. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  52237. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  52238. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  52239. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  52240. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  52241. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  52242. this._engine.bindArrayBuffer(null);
  52243. return vao;
  52244. };
  52245. GPUParticleSystem.prototype._initialize = function (force) {
  52246. if (force === void 0) { force = false; }
  52247. if (this._buffer0 && !force) {
  52248. return;
  52249. }
  52250. var engine = this._scene.getEngine();
  52251. var data = new Array();
  52252. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  52253. // position
  52254. data.push(0.0);
  52255. data.push(0.0);
  52256. data.push(0.0);
  52257. // Age and life
  52258. data.push(0.0); // create the particle as a dead one to create a new one at start
  52259. data.push(0.0);
  52260. // Seed
  52261. data.push(Math.random());
  52262. // Size
  52263. data.push(0.0);
  52264. // color
  52265. data.push(0.0);
  52266. data.push(0.0);
  52267. data.push(0.0);
  52268. data.push(0.0);
  52269. // direction
  52270. data.push(0.0);
  52271. data.push(0.0);
  52272. data.push(0.0);
  52273. }
  52274. // Sprite data
  52275. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  52276. -0.5, 0.5, 0, 1,
  52277. -0.5, -0.5, 0, 0,
  52278. 0.5, -0.5, 1, 0]);
  52279. // Buffers
  52280. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  52281. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  52282. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  52283. // Update VAO
  52284. this._updateVAO = [];
  52285. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  52286. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  52287. // Render VAO
  52288. this._renderVAO = [];
  52289. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  52290. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  52291. // Links
  52292. this._sourceBuffer = this._buffer0;
  52293. this._targetBuffer = this._buffer1;
  52294. };
  52295. /** @ignore */
  52296. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  52297. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  52298. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  52299. return;
  52300. }
  52301. this._updateEffectOptions.defines = defines;
  52302. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  52303. };
  52304. /** @ignore */
  52305. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  52306. var defines = "";
  52307. if (this._scene.clipPlane) {
  52308. defines = "\n#define CLIPPLANE";
  52309. }
  52310. if (this._renderEffect && this._renderEffect.defines === defines) {
  52311. return;
  52312. }
  52313. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  52314. };
  52315. /**
  52316. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  52317. */
  52318. GPUParticleSystem.prototype.animate = function () {
  52319. if (!this._stopped) {
  52320. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  52321. this._actualFrame += this._timeDelta;
  52322. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  52323. this.stop();
  52324. }
  52325. else {
  52326. this._timeDelta = 0;
  52327. }
  52328. };
  52329. /**
  52330. * Renders the particle system in its current state.
  52331. * @returns the current number of particles
  52332. */
  52333. GPUParticleSystem.prototype.render = function () {
  52334. if (!this._started) {
  52335. return 0;
  52336. }
  52337. this._recreateUpdateEffect();
  52338. this._recreateRenderEffect();
  52339. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady()) {
  52340. return 0;
  52341. }
  52342. if (this._currentRenderId === this._scene.getRenderId()) {
  52343. return 0;
  52344. }
  52345. this._currentRenderId = this._scene.getRenderId();
  52346. // Get everything ready to render
  52347. this._initialize();
  52348. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  52349. // Enable update effect
  52350. this._engine.enableEffect(this._updateEffect);
  52351. this._engine.setState(false);
  52352. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  52353. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  52354. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  52355. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  52356. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  52357. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  52358. this._updateEffect.setDirectColor4("color1", this.color1);
  52359. this._updateEffect.setDirectColor4("color2", this.color2);
  52360. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  52361. this._updateEffect.setVector3("gravity", this.gravity);
  52362. if (this.particleEmitterType) {
  52363. this.particleEmitterType.applyToShader(this._updateEffect);
  52364. }
  52365. var emitterWM;
  52366. if (this.emitter.position) {
  52367. var emitterMesh = this.emitter;
  52368. emitterWM = emitterMesh.getWorldMatrix();
  52369. }
  52370. else {
  52371. var emitterPosition = this.emitter;
  52372. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  52373. }
  52374. this._updateEffect.setMatrix("emitterWM", emitterWM);
  52375. // Bind source VAO
  52376. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  52377. // Update
  52378. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  52379. this._engine.setRasterizerState(false);
  52380. this._engine.beginTransformFeedback();
  52381. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  52382. this._engine.endTransformFeedback();
  52383. this._engine.setRasterizerState(true);
  52384. this._engine.bindTransformFeedbackBuffer(null);
  52385. // Enable render effect
  52386. this._engine.enableEffect(this._renderEffect);
  52387. var viewMatrix = this._scene.getViewMatrix();
  52388. this._renderEffect.setMatrix("view", viewMatrix);
  52389. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  52390. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  52391. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  52392. if (this._scene.clipPlane) {
  52393. var clipPlane = this._scene.clipPlane;
  52394. var invView = viewMatrix.clone();
  52395. invView.invert();
  52396. this._renderEffect.setMatrix("invView", invView);
  52397. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  52398. }
  52399. // Draw order
  52400. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  52401. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  52402. }
  52403. else {
  52404. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52405. }
  52406. // Bind source VAO
  52407. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  52408. // Render
  52409. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  52410. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52411. // Switch VAOs
  52412. this._targetIndex++;
  52413. if (this._targetIndex === 2) {
  52414. this._targetIndex = 0;
  52415. }
  52416. // Switch buffers
  52417. var tmpBuffer = this._sourceBuffer;
  52418. this._sourceBuffer = this._targetBuffer;
  52419. this._targetBuffer = tmpBuffer;
  52420. return this._currentActiveCount;
  52421. };
  52422. /**
  52423. * Rebuilds the particle system
  52424. */
  52425. GPUParticleSystem.prototype.rebuild = function () {
  52426. this._initialize(true);
  52427. };
  52428. GPUParticleSystem.prototype._releaseBuffers = function () {
  52429. if (this._buffer0) {
  52430. this._buffer0.dispose();
  52431. this._buffer0 = null;
  52432. }
  52433. if (this._buffer1) {
  52434. this._buffer1.dispose();
  52435. this._buffer1 = null;
  52436. }
  52437. if (this._spriteBuffer) {
  52438. this._spriteBuffer.dispose();
  52439. this._spriteBuffer = null;
  52440. }
  52441. };
  52442. GPUParticleSystem.prototype._releaseVAOs = function () {
  52443. for (var index = 0; index < this._updateVAO.length; index++) {
  52444. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  52445. }
  52446. this._updateVAO = [];
  52447. for (var index = 0; index < this._renderVAO.length; index++) {
  52448. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  52449. }
  52450. this._renderVAO = [];
  52451. };
  52452. /**
  52453. * Disposes the particle system and free the associated resources
  52454. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  52455. */
  52456. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  52457. if (disposeTexture === void 0) { disposeTexture = true; }
  52458. var index = this._scene.particleSystems.indexOf(this);
  52459. if (index > -1) {
  52460. this._scene.particleSystems.splice(index, 1);
  52461. }
  52462. this._releaseBuffers();
  52463. this._releaseVAOs();
  52464. if (this._randomTexture) {
  52465. this._randomTexture.dispose();
  52466. this._randomTexture = null;
  52467. }
  52468. if (disposeTexture && this.particleTexture) {
  52469. this.particleTexture.dispose();
  52470. this.particleTexture = null;
  52471. }
  52472. // Callback
  52473. this.onDisposeObservable.notifyObservers(this);
  52474. this.onDisposeObservable.clear();
  52475. };
  52476. /**
  52477. * Clones the particle system.
  52478. * @param name The name of the cloned object
  52479. * @param newEmitter The new emitter to use
  52480. * @returns the cloned particle system
  52481. */
  52482. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  52483. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  52484. BABYLON.Tools.DeepCopy(this, result);
  52485. if (newEmitter === undefined) {
  52486. newEmitter = this.emitter;
  52487. }
  52488. result.emitter = newEmitter;
  52489. if (this.particleTexture) {
  52490. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  52491. }
  52492. return result;
  52493. };
  52494. /**
  52495. * Serializes the particle system to a JSON object.
  52496. * @returns the JSON object
  52497. */
  52498. GPUParticleSystem.prototype.serialize = function () {
  52499. var serializationObject = {};
  52500. serializationObject.name = this.name;
  52501. serializationObject.id = this.id;
  52502. // Emitter
  52503. if (this.emitter.position) {
  52504. var emitterMesh = this.emitter;
  52505. serializationObject.emitterId = emitterMesh.id;
  52506. }
  52507. else {
  52508. var emitterPosition = this.emitter;
  52509. serializationObject.emitter = emitterPosition.asArray();
  52510. }
  52511. serializationObject.capacity = this.getCapacity();
  52512. if (this.particleTexture) {
  52513. serializationObject.textureName = this.particleTexture.name;
  52514. }
  52515. // Animations
  52516. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  52517. // Particle system
  52518. serializationObject.activeParticleCount = this.activeParticleCount;
  52519. serializationObject.randomTextureSize = this._randomTextureSize;
  52520. serializationObject.minSize = this.minSize;
  52521. serializationObject.maxSize = this.maxSize;
  52522. serializationObject.minEmitPower = this.minEmitPower;
  52523. serializationObject.maxEmitPower = this.maxEmitPower;
  52524. serializationObject.minLifeTime = this.minLifeTime;
  52525. serializationObject.maxLifeTime = this.maxLifeTime;
  52526. serializationObject.emitRate = this.emitRate;
  52527. serializationObject.gravity = this.gravity.asArray();
  52528. serializationObject.color1 = this.color1.asArray();
  52529. serializationObject.color2 = this.color2.asArray();
  52530. serializationObject.colorDead = this.colorDead.asArray();
  52531. serializationObject.updateSpeed = this.updateSpeed;
  52532. serializationObject.targetStopDuration = this.targetStopDuration;
  52533. serializationObject.blendMode = this.blendMode;
  52534. // Emitter
  52535. if (this.particleEmitterType) {
  52536. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  52537. }
  52538. return serializationObject;
  52539. };
  52540. /**
  52541. * Parses a JSON object to create a GPU particle system.
  52542. * @param parsedParticleSystem The JSON object to parse
  52543. * @param scene The scene to create the particle system in
  52544. * @param rootUrl The root url to use to load external dependencies like texture
  52545. * @returns the parsed GPU particle system
  52546. */
  52547. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  52548. var name = parsedParticleSystem.name;
  52549. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  52550. if (parsedParticleSystem.id) {
  52551. particleSystem.id = parsedParticleSystem.id;
  52552. }
  52553. // Texture
  52554. if (parsedParticleSystem.textureName) {
  52555. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  52556. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  52557. }
  52558. // Emitter
  52559. if (parsedParticleSystem.emitterId) {
  52560. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  52561. }
  52562. else {
  52563. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  52564. }
  52565. // Animations
  52566. if (parsedParticleSystem.animations) {
  52567. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  52568. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  52569. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  52570. }
  52571. }
  52572. // Particle system
  52573. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  52574. particleSystem.minSize = parsedParticleSystem.minSize;
  52575. particleSystem.maxSize = parsedParticleSystem.maxSize;
  52576. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  52577. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  52578. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  52579. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  52580. particleSystem.emitRate = parsedParticleSystem.emitRate;
  52581. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  52582. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  52583. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  52584. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  52585. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  52586. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  52587. particleSystem.blendMode = parsedParticleSystem.blendMode;
  52588. // Emitter
  52589. if (parsedParticleSystem.particleEmitterType) {
  52590. var emitterType = void 0;
  52591. switch (parsedParticleSystem.particleEmitterType.type) {
  52592. case "SphereEmitter":
  52593. emitterType = new BABYLON.SphereParticleEmitter();
  52594. break;
  52595. case "SphereDirectedParticleEmitter":
  52596. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  52597. break;
  52598. case "ConeEmitter":
  52599. emitterType = new BABYLON.ConeParticleEmitter();
  52600. break;
  52601. case "BoxEmitter":
  52602. default:
  52603. emitterType = new BABYLON.BoxParticleEmitter();
  52604. break;
  52605. }
  52606. emitterType.parse(parsedParticleSystem.particleEmitterType);
  52607. particleSystem.particleEmitterType = emitterType;
  52608. }
  52609. return particleSystem;
  52610. };
  52611. return GPUParticleSystem;
  52612. }());
  52613. BABYLON.GPUParticleSystem = GPUParticleSystem;
  52614. })(BABYLON || (BABYLON = {}));
  52615. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  52616. var BABYLON;
  52617. (function (BABYLON) {
  52618. /**
  52619. * Represents one particle of a solid particle system.
  52620. * @see SolidParticleSystem
  52621. */
  52622. var SolidParticle = /** @class */ (function () {
  52623. /**
  52624. * Creates a Solid Particle object.
  52625. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  52626. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  52627. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  52628. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  52629. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  52630. * @param shapeId (integer) is the model shape identifier in the SPS.
  52631. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  52632. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  52633. */
  52634. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  52635. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  52636. /**
  52637. * particle global index
  52638. */
  52639. this.idx = 0;
  52640. /**
  52641. * The color of the particle
  52642. */
  52643. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52644. /**
  52645. * The world space position of the particle.
  52646. */
  52647. this.position = BABYLON.Vector3.Zero();
  52648. /**
  52649. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  52650. */
  52651. this.rotation = BABYLON.Vector3.Zero();
  52652. /**
  52653. * The scaling of the particle.
  52654. */
  52655. this.scaling = BABYLON.Vector3.One();
  52656. /**
  52657. * The uvs of the particle.
  52658. */
  52659. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  52660. /**
  52661. * The current speed of the particle.
  52662. */
  52663. this.velocity = BABYLON.Vector3.Zero();
  52664. /**
  52665. * The pivot point in the particle local space.
  52666. */
  52667. this.pivot = BABYLON.Vector3.Zero();
  52668. /**
  52669. * Must the particle be translated from its pivot point in its local space ?
  52670. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  52671. * Default : false
  52672. */
  52673. this.translateFromPivot = false;
  52674. /**
  52675. * Is the particle active or not ?
  52676. */
  52677. this.alive = true;
  52678. /**
  52679. * Is the particle visible or not ?
  52680. */
  52681. this.isVisible = true;
  52682. /**
  52683. * Index of this particle in the global "positions" array (Internal use)
  52684. */
  52685. this._pos = 0;
  52686. /**
  52687. * Index of this particle in the global "indices" array (Internal use)
  52688. */
  52689. this._ind = 0;
  52690. /**
  52691. * ModelShape id of this particle
  52692. */
  52693. this.shapeId = 0;
  52694. /**
  52695. * Index of the particle in its shape id (Internal use)
  52696. */
  52697. this.idxInShape = 0;
  52698. /**
  52699. * Still set as invisible in order to skip useless computations (Internal use)
  52700. */
  52701. this._stillInvisible = false;
  52702. /**
  52703. * Last computed particle rotation matrix
  52704. */
  52705. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  52706. /**
  52707. * Parent particle Id, if any.
  52708. * Default null.
  52709. */
  52710. this.parentId = null;
  52711. /**
  52712. * Internal global position in the SPS.
  52713. */
  52714. this._globalPosition = BABYLON.Vector3.Zero();
  52715. this.idx = particleIndex;
  52716. this._pos = positionIndex;
  52717. this._ind = indiceIndex;
  52718. this._model = model;
  52719. this.shapeId = shapeId;
  52720. this.idxInShape = idxInShape;
  52721. this._sps = sps;
  52722. if (modelBoundingInfo) {
  52723. this._modelBoundingInfo = modelBoundingInfo;
  52724. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  52725. }
  52726. }
  52727. Object.defineProperty(SolidParticle.prototype, "scale", {
  52728. /**
  52729. * Legacy support, changed scale to scaling
  52730. */
  52731. get: function () {
  52732. return this.scaling;
  52733. },
  52734. /**
  52735. * Legacy support, changed scale to scaling
  52736. */
  52737. set: function (scale) {
  52738. this.scaling = scale;
  52739. },
  52740. enumerable: true,
  52741. configurable: true
  52742. });
  52743. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  52744. /**
  52745. * Legacy support, changed quaternion to rotationQuaternion
  52746. */
  52747. get: function () {
  52748. return this.rotationQuaternion;
  52749. },
  52750. /**
  52751. * Legacy support, changed quaternion to rotationQuaternion
  52752. */
  52753. set: function (q) {
  52754. this.rotationQuaternion = q;
  52755. },
  52756. enumerable: true,
  52757. configurable: true
  52758. });
  52759. /**
  52760. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  52761. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  52762. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  52763. * @returns true if it intersects
  52764. */
  52765. SolidParticle.prototype.intersectsMesh = function (target) {
  52766. if (!this._boundingInfo || !target._boundingInfo) {
  52767. return false;
  52768. }
  52769. if (this._sps._bSphereOnly) {
  52770. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  52771. }
  52772. return this._boundingInfo.intersects(target._boundingInfo, false);
  52773. };
  52774. return SolidParticle;
  52775. }());
  52776. BABYLON.SolidParticle = SolidParticle;
  52777. /**
  52778. * Represents the shape of the model used by one particle of a solid particle system.
  52779. * SPS internal tool, don't use it manually.
  52780. * @see SolidParticleSystem
  52781. */
  52782. var ModelShape = /** @class */ (function () {
  52783. /**
  52784. * 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.
  52785. * SPS internal tool, don't use it manually.
  52786. * @ignore
  52787. */
  52788. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  52789. /**
  52790. * length of the shape in the model indices array (internal use)
  52791. */
  52792. this._indicesLength = 0;
  52793. this.shapeID = id;
  52794. this._shape = shape;
  52795. this._indicesLength = indicesLength;
  52796. this._shapeUV = shapeUV;
  52797. this._positionFunction = posFunction;
  52798. this._vertexFunction = vtxFunction;
  52799. }
  52800. return ModelShape;
  52801. }());
  52802. BABYLON.ModelShape = ModelShape;
  52803. /**
  52804. * Represents a Depth Sorted Particle in the solid particle system.
  52805. * @see SolidParticleSystem
  52806. */
  52807. var DepthSortedParticle = /** @class */ (function () {
  52808. function DepthSortedParticle() {
  52809. /**
  52810. * Index of the particle in the "indices" array
  52811. */
  52812. this.ind = 0;
  52813. /**
  52814. * Length of the particle shape in the "indices" array
  52815. */
  52816. this.indicesLength = 0;
  52817. /**
  52818. * Squared distance from the particle to the camera
  52819. */
  52820. this.sqDistance = 0.0;
  52821. }
  52822. return DepthSortedParticle;
  52823. }());
  52824. BABYLON.DepthSortedParticle = DepthSortedParticle;
  52825. })(BABYLON || (BABYLON = {}));
  52826. //# sourceMappingURL=babylon.solidParticle.js.map
  52827. var BABYLON;
  52828. (function (BABYLON) {
  52829. /**
  52830. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  52831. *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.
  52832. * The SPS is also a particle system. It provides some methods to manage the particles.
  52833. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  52834. *
  52835. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  52836. */
  52837. var SolidParticleSystem = /** @class */ (function () {
  52838. /**
  52839. * Creates a SPS (Solid Particle System) object.
  52840. * @param name (String) is the SPS name, this will be the underlying mesh name.
  52841. * @param scene (Scene) is the scene in which the SPS is added.
  52842. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  52843. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  52844. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  52845. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  52846. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  52847. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  52848. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  52849. */
  52850. function SolidParticleSystem(name, scene, options) {
  52851. /**
  52852. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  52853. * Example : var p = SPS.particles[i];
  52854. */
  52855. this.particles = new Array();
  52856. /**
  52857. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  52858. */
  52859. this.nbParticles = 0;
  52860. /**
  52861. * If the particles must ever face the camera (default false). Useful for planar particles.
  52862. */
  52863. this.billboard = false;
  52864. /**
  52865. * Recompute normals when adding a shape
  52866. */
  52867. this.recomputeNormals = true;
  52868. /**
  52869. * This a counter ofr your own usage. It's not set by any SPS functions.
  52870. */
  52871. this.counter = 0;
  52872. /**
  52873. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  52874. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  52875. */
  52876. this.vars = {};
  52877. /**
  52878. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  52879. */
  52880. this._bSphereOnly = false;
  52881. /**
  52882. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  52883. */
  52884. this._bSphereRadiusFactor = 1.0;
  52885. this._positions = new Array();
  52886. this._indices = new Array();
  52887. this._normals = new Array();
  52888. this._colors = new Array();
  52889. this._uvs = new Array();
  52890. this._index = 0; // indices index
  52891. this._updatable = true;
  52892. this._pickable = false;
  52893. this._isVisibilityBoxLocked = false;
  52894. this._alwaysVisible = false;
  52895. this._depthSort = false;
  52896. this._shapeCounter = 0;
  52897. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  52898. this._color = new BABYLON.Color4(0, 0, 0, 0);
  52899. this._computeParticleColor = true;
  52900. this._computeParticleTexture = true;
  52901. this._computeParticleRotation = true;
  52902. this._computeParticleVertex = false;
  52903. this._computeBoundingBox = false;
  52904. this._depthSortParticles = true;
  52905. this._cam_axisZ = BABYLON.Vector3.Zero();
  52906. this._cam_axisY = BABYLON.Vector3.Zero();
  52907. this._cam_axisX = BABYLON.Vector3.Zero();
  52908. this._axisZ = BABYLON.Axis.Z;
  52909. this._camDir = BABYLON.Vector3.Zero();
  52910. this._camInvertedPosition = BABYLON.Vector3.Zero();
  52911. this._rotMatrix = new BABYLON.Matrix();
  52912. this._invertMatrix = new BABYLON.Matrix();
  52913. this._rotated = BABYLON.Vector3.Zero();
  52914. this._quaternion = new BABYLON.Quaternion();
  52915. this._vertex = BABYLON.Vector3.Zero();
  52916. this._normal = BABYLON.Vector3.Zero();
  52917. this._yaw = 0.0;
  52918. this._pitch = 0.0;
  52919. this._roll = 0.0;
  52920. this._halfroll = 0.0;
  52921. this._halfpitch = 0.0;
  52922. this._halfyaw = 0.0;
  52923. this._sinRoll = 0.0;
  52924. this._cosRoll = 0.0;
  52925. this._sinPitch = 0.0;
  52926. this._cosPitch = 0.0;
  52927. this._sinYaw = 0.0;
  52928. this._cosYaw = 0.0;
  52929. this._mustUnrotateFixedNormals = false;
  52930. this._minimum = BABYLON.Vector3.Zero();
  52931. this._maximum = BABYLON.Vector3.Zero();
  52932. this._minBbox = BABYLON.Vector3.Zero();
  52933. this._maxBbox = BABYLON.Vector3.Zero();
  52934. this._particlesIntersect = false;
  52935. this._depthSortFunction = function (p1, p2) {
  52936. return (p2.sqDistance - p1.sqDistance);
  52937. };
  52938. this._needs32Bits = false;
  52939. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  52940. this._scaledPivot = BABYLON.Vector3.Zero();
  52941. this._particleHasParent = false;
  52942. this.name = name;
  52943. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52944. this._camera = scene.activeCamera;
  52945. this._pickable = options ? options.isPickable : false;
  52946. this._depthSort = options ? options.enableDepthSort : false;
  52947. this._particlesIntersect = options ? options.particleIntersection : false;
  52948. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  52949. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  52950. if (options && options.updatable) {
  52951. this._updatable = options.updatable;
  52952. }
  52953. else {
  52954. this._updatable = true;
  52955. }
  52956. if (this._pickable) {
  52957. this.pickedParticles = [];
  52958. }
  52959. if (this._depthSort) {
  52960. this.depthSortedParticles = [];
  52961. }
  52962. }
  52963. /**
  52964. * Builds the SPS underlying mesh. Returns a standard Mesh.
  52965. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  52966. * @returns the created mesh
  52967. */
  52968. SolidParticleSystem.prototype.buildMesh = function () {
  52969. if (this.nbParticles === 0) {
  52970. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  52971. this.addShape(triangle, 1);
  52972. triangle.dispose();
  52973. }
  52974. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  52975. this._positions32 = new Float32Array(this._positions);
  52976. this._uvs32 = new Float32Array(this._uvs);
  52977. this._colors32 = new Float32Array(this._colors);
  52978. if (this.recomputeNormals) {
  52979. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  52980. }
  52981. this._normals32 = new Float32Array(this._normals);
  52982. this._fixedNormal32 = new Float32Array(this._normals);
  52983. if (this._mustUnrotateFixedNormals) {
  52984. this._unrotateFixedNormals();
  52985. }
  52986. var vertexData = new BABYLON.VertexData();
  52987. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  52988. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  52989. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  52990. if (this._uvs32) {
  52991. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  52992. ;
  52993. }
  52994. if (this._colors32) {
  52995. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  52996. }
  52997. var mesh = new BABYLON.Mesh(this.name, this._scene);
  52998. vertexData.applyToMesh(mesh, this._updatable);
  52999. this.mesh = mesh;
  53000. this.mesh.isPickable = this._pickable;
  53001. // free memory
  53002. if (!this._depthSort) {
  53003. this._indices = null;
  53004. }
  53005. this._positions = null;
  53006. this._normals = null;
  53007. this._uvs = null;
  53008. this._colors = null;
  53009. if (!this._updatable) {
  53010. this.particles.length = 0;
  53011. }
  53012. return mesh;
  53013. };
  53014. /**
  53015. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  53016. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  53017. * Thus the particles generated from `digest()` have their property `position` set yet.
  53018. * @param mesh ( Mesh ) is the mesh to be digested
  53019. * @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
  53020. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  53021. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  53022. * @returns the current SPS
  53023. */
  53024. SolidParticleSystem.prototype.digest = function (mesh, options) {
  53025. var size = (options && options.facetNb) || 1;
  53026. var number = (options && options.number) || 0;
  53027. var delta = (options && options.delta) || 0;
  53028. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53029. var meshInd = mesh.getIndices();
  53030. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53031. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53032. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53033. var f = 0; // facet counter
  53034. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  53035. // compute size from number
  53036. if (number) {
  53037. number = (number > totalFacets) ? totalFacets : number;
  53038. size = Math.round(totalFacets / number);
  53039. delta = 0;
  53040. }
  53041. else {
  53042. size = (size > totalFacets) ? totalFacets : size;
  53043. }
  53044. var facetPos = []; // submesh positions
  53045. var facetInd = []; // submesh indices
  53046. var facetUV = []; // submesh UV
  53047. var facetCol = []; // submesh colors
  53048. var barycenter = BABYLON.Vector3.Zero();
  53049. var sizeO = size;
  53050. while (f < totalFacets) {
  53051. size = sizeO + Math.floor((1 + delta) * Math.random());
  53052. if (f > totalFacets - size) {
  53053. size = totalFacets - f;
  53054. }
  53055. // reset temp arrays
  53056. facetPos.length = 0;
  53057. facetInd.length = 0;
  53058. facetUV.length = 0;
  53059. facetCol.length = 0;
  53060. // iterate over "size" facets
  53061. var fi = 0;
  53062. for (var j = f * 3; j < (f + size) * 3; j++) {
  53063. facetInd.push(fi);
  53064. var i = meshInd[j];
  53065. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  53066. if (meshUV) {
  53067. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  53068. }
  53069. if (meshCol) {
  53070. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  53071. }
  53072. fi++;
  53073. }
  53074. // create a model shape for each single particle
  53075. var idx = this.nbParticles;
  53076. var shape = this._posToShape(facetPos);
  53077. var shapeUV = this._uvsToShapeUV(facetUV);
  53078. // compute the barycenter of the shape
  53079. var v;
  53080. for (v = 0; v < shape.length; v++) {
  53081. barycenter.addInPlace(shape[v]);
  53082. }
  53083. barycenter.scaleInPlace(1 / shape.length);
  53084. // shift the shape from its barycenter to the origin
  53085. for (v = 0; v < shape.length; v++) {
  53086. shape[v].subtractInPlace(barycenter);
  53087. }
  53088. var bInfo;
  53089. if (this._particlesIntersect) {
  53090. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  53091. }
  53092. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  53093. // add the particle in the SPS
  53094. var currentPos = this._positions.length;
  53095. var currentInd = this._indices.length;
  53096. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  53097. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  53098. // initialize the particle position
  53099. this.particles[this.nbParticles].position.addInPlace(barycenter);
  53100. this._index += shape.length;
  53101. idx++;
  53102. this.nbParticles++;
  53103. this._shapeCounter++;
  53104. f += size;
  53105. }
  53106. return this;
  53107. };
  53108. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  53109. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  53110. var index = 0;
  53111. var idx = 0;
  53112. for (var p = 0; p < this.particles.length; p++) {
  53113. this._particle = this.particles[p];
  53114. this._shape = this._particle._model._shape;
  53115. if (this._particle.rotationQuaternion) {
  53116. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  53117. }
  53118. else {
  53119. this._yaw = this._particle.rotation.y;
  53120. this._pitch = this._particle.rotation.x;
  53121. this._roll = this._particle.rotation.z;
  53122. this._quaternionRotationYPR();
  53123. }
  53124. this._quaternionToRotationMatrix();
  53125. this._rotMatrix.invertToRef(this._invertMatrix);
  53126. for (var pt = 0; pt < this._shape.length; pt++) {
  53127. idx = index + pt * 3;
  53128. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  53129. this._fixedNormal32[idx] = this._normal.x;
  53130. this._fixedNormal32[idx + 1] = this._normal.y;
  53131. this._fixedNormal32[idx + 2] = this._normal.z;
  53132. }
  53133. index = idx + 3;
  53134. }
  53135. };
  53136. //reset copy
  53137. SolidParticleSystem.prototype._resetCopy = function () {
  53138. this._copy.position.x = 0;
  53139. this._copy.position.y = 0;
  53140. this._copy.position.z = 0;
  53141. this._copy.rotation.x = 0;
  53142. this._copy.rotation.y = 0;
  53143. this._copy.rotation.z = 0;
  53144. this._copy.rotationQuaternion = null;
  53145. this._copy.scaling.x = 1.0;
  53146. this._copy.scaling.y = 1.0;
  53147. this._copy.scaling.z = 1.0;
  53148. this._copy.uvs.x = 0;
  53149. this._copy.uvs.y = 0;
  53150. this._copy.uvs.z = 1.0;
  53151. this._copy.uvs.w = 1.0;
  53152. this._copy.color = null;
  53153. this._copy.translateFromPivot = false;
  53154. };
  53155. // _meshBuilder : inserts the shape model in the global SPS mesh
  53156. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  53157. var i;
  53158. var u = 0;
  53159. var c = 0;
  53160. var n = 0;
  53161. this._resetCopy();
  53162. if (options && options.positionFunction) {
  53163. options.positionFunction(this._copy, idx, idxInShape);
  53164. this._mustUnrotateFixedNormals = true;
  53165. }
  53166. if (this._copy.rotationQuaternion) {
  53167. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  53168. }
  53169. else {
  53170. this._yaw = this._copy.rotation.y;
  53171. this._pitch = this._copy.rotation.x;
  53172. this._roll = this._copy.rotation.z;
  53173. this._quaternionRotationYPR();
  53174. }
  53175. this._quaternionToRotationMatrix();
  53176. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  53177. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  53178. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  53179. if (this._copy.translateFromPivot) {
  53180. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  53181. }
  53182. else {
  53183. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  53184. }
  53185. for (i = 0; i < shape.length; i++) {
  53186. this._vertex.x = shape[i].x;
  53187. this._vertex.y = shape[i].y;
  53188. this._vertex.z = shape[i].z;
  53189. if (options && options.vertexFunction) {
  53190. options.vertexFunction(this._copy, this._vertex, i);
  53191. }
  53192. this._vertex.x *= this._copy.scaling.x;
  53193. this._vertex.y *= this._copy.scaling.y;
  53194. this._vertex.z *= this._copy.scaling.z;
  53195. this._vertex.x -= this._scaledPivot.x;
  53196. this._vertex.y -= this._scaledPivot.y;
  53197. this._vertex.z -= this._scaledPivot.z;
  53198. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  53199. this._rotated.addInPlace(this._pivotBackTranslation);
  53200. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  53201. if (meshUV) {
  53202. 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);
  53203. u += 2;
  53204. }
  53205. if (this._copy.color) {
  53206. this._color = this._copy.color;
  53207. }
  53208. else if (meshCol && meshCol[c] !== undefined) {
  53209. this._color.r = meshCol[c];
  53210. this._color.g = meshCol[c + 1];
  53211. this._color.b = meshCol[c + 2];
  53212. this._color.a = meshCol[c + 3];
  53213. }
  53214. else {
  53215. this._color.r = 1.0;
  53216. this._color.g = 1.0;
  53217. this._color.b = 1.0;
  53218. this._color.a = 1.0;
  53219. }
  53220. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  53221. c += 4;
  53222. if (!this.recomputeNormals && meshNor) {
  53223. this._normal.x = meshNor[n];
  53224. this._normal.y = meshNor[n + 1];
  53225. this._normal.z = meshNor[n + 2];
  53226. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  53227. normals.push(this._normal.x, this._normal.y, this._normal.z);
  53228. n += 3;
  53229. }
  53230. }
  53231. for (i = 0; i < meshInd.length; i++) {
  53232. var current_ind = p + meshInd[i];
  53233. indices.push(current_ind);
  53234. if (current_ind > 65535) {
  53235. this._needs32Bits = true;
  53236. }
  53237. }
  53238. if (this._pickable) {
  53239. var nbfaces = meshInd.length / 3;
  53240. for (i = 0; i < nbfaces; i++) {
  53241. this.pickedParticles.push({ idx: idx, faceId: i });
  53242. }
  53243. }
  53244. if (this._depthSort) {
  53245. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  53246. }
  53247. return this._copy;
  53248. };
  53249. // returns a shape array from positions array
  53250. SolidParticleSystem.prototype._posToShape = function (positions) {
  53251. var shape = [];
  53252. for (var i = 0; i < positions.length; i += 3) {
  53253. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  53254. }
  53255. return shape;
  53256. };
  53257. // returns a shapeUV array from a Vector4 uvs
  53258. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  53259. var shapeUV = [];
  53260. if (uvs) {
  53261. for (var i = 0; i < uvs.length; i++)
  53262. shapeUV.push(uvs[i]);
  53263. }
  53264. return shapeUV;
  53265. };
  53266. // adds a new particle object in the particles array
  53267. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  53268. if (bInfo === void 0) { bInfo = null; }
  53269. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  53270. this.particles.push(sp);
  53271. return sp;
  53272. };
  53273. /**
  53274. * Adds some particles to the SPS from the model shape. Returns the shape id.
  53275. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  53276. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  53277. * @param nb (positive integer) the number of particles to be created from this model
  53278. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  53279. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  53280. * @returns the number of shapes in the system
  53281. */
  53282. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  53283. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53284. var meshInd = mesh.getIndices();
  53285. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53286. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53287. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53288. var bbInfo;
  53289. if (this._particlesIntersect) {
  53290. bbInfo = mesh.getBoundingInfo();
  53291. }
  53292. var shape = this._posToShape(meshPos);
  53293. var shapeUV = this._uvsToShapeUV(meshUV);
  53294. var posfunc = options ? options.positionFunction : null;
  53295. var vtxfunc = options ? options.vertexFunction : null;
  53296. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  53297. // particles
  53298. var sp;
  53299. var currentCopy;
  53300. var idx = this.nbParticles;
  53301. for (var i = 0; i < nb; i++) {
  53302. var currentPos = this._positions.length;
  53303. var currentInd = this._indices.length;
  53304. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  53305. if (this._updatable) {
  53306. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  53307. sp.position.copyFrom(currentCopy.position);
  53308. sp.rotation.copyFrom(currentCopy.rotation);
  53309. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  53310. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  53311. }
  53312. if (currentCopy.color && sp.color) {
  53313. sp.color.copyFrom(currentCopy.color);
  53314. }
  53315. sp.scaling.copyFrom(currentCopy.scaling);
  53316. sp.uvs.copyFrom(currentCopy.uvs);
  53317. }
  53318. this._index += shape.length;
  53319. idx++;
  53320. }
  53321. this.nbParticles += nb;
  53322. this._shapeCounter++;
  53323. return this._shapeCounter - 1;
  53324. };
  53325. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  53326. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  53327. this._resetCopy();
  53328. if (particle._model._positionFunction) {
  53329. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  53330. }
  53331. if (this._copy.rotationQuaternion) {
  53332. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  53333. }
  53334. else {
  53335. this._yaw = this._copy.rotation.y;
  53336. this._pitch = this._copy.rotation.x;
  53337. this._roll = this._copy.rotation.z;
  53338. this._quaternionRotationYPR();
  53339. }
  53340. this._quaternionToRotationMatrix();
  53341. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  53342. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  53343. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  53344. if (this._copy.translateFromPivot) {
  53345. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  53346. }
  53347. else {
  53348. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  53349. }
  53350. this._shape = particle._model._shape;
  53351. for (var pt = 0; pt < this._shape.length; pt++) {
  53352. this._vertex.x = this._shape[pt].x;
  53353. this._vertex.y = this._shape[pt].y;
  53354. this._vertex.z = this._shape[pt].z;
  53355. if (particle._model._vertexFunction) {
  53356. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  53357. }
  53358. this._vertex.x *= this._copy.scaling.x;
  53359. this._vertex.y *= this._copy.scaling.y;
  53360. this._vertex.z *= this._copy.scaling.z;
  53361. this._vertex.x -= this._scaledPivot.x;
  53362. this._vertex.y -= this._scaledPivot.y;
  53363. this._vertex.z -= this._scaledPivot.z;
  53364. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  53365. this._rotated.addInPlace(this._pivotBackTranslation);
  53366. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  53367. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  53368. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  53369. }
  53370. particle.position.x = 0.0;
  53371. particle.position.y = 0.0;
  53372. particle.position.z = 0.0;
  53373. particle.rotation.x = 0.0;
  53374. particle.rotation.y = 0.0;
  53375. particle.rotation.z = 0.0;
  53376. particle.rotationQuaternion = null;
  53377. particle.scaling.x = 1.0;
  53378. particle.scaling.y = 1.0;
  53379. particle.scaling.z = 1.0;
  53380. particle.uvs.x = 0.0;
  53381. particle.uvs.y = 0.0;
  53382. particle.uvs.z = 1.0;
  53383. particle.uvs.w = 1.0;
  53384. particle.pivot.x = 0.0;
  53385. particle.pivot.y = 0.0;
  53386. particle.pivot.z = 0.0;
  53387. particle.translateFromPivot = false;
  53388. particle.parentId = null;
  53389. };
  53390. /**
  53391. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  53392. * @returns the SPS.
  53393. */
  53394. SolidParticleSystem.prototype.rebuildMesh = function () {
  53395. for (var p = 0; p < this.particles.length; p++) {
  53396. this._rebuildParticle(this.particles[p]);
  53397. }
  53398. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53399. return this;
  53400. };
  53401. /**
  53402. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  53403. * This method calls `updateParticle()` for each particle of the SPS.
  53404. * For an animated SPS, it is usually called within the render loop.
  53405. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  53406. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  53407. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  53408. * @returns the SPS.
  53409. */
  53410. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  53411. if (start === void 0) { start = 0; }
  53412. if (end === void 0) { end = this.nbParticles - 1; }
  53413. if (update === void 0) { update = true; }
  53414. if (!this._updatable) {
  53415. return this;
  53416. }
  53417. // custom beforeUpdate
  53418. this.beforeUpdateParticles(start, end, update);
  53419. this._cam_axisX.x = 1.0;
  53420. this._cam_axisX.y = 0.0;
  53421. this._cam_axisX.z = 0.0;
  53422. this._cam_axisY.x = 0.0;
  53423. this._cam_axisY.y = 1.0;
  53424. this._cam_axisY.z = 0.0;
  53425. this._cam_axisZ.x = 0.0;
  53426. this._cam_axisZ.y = 0.0;
  53427. this._cam_axisZ.z = 1.0;
  53428. // cases when the World Matrix is to be computed first
  53429. if (this.billboard || this._depthSort) {
  53430. this.mesh.computeWorldMatrix(true);
  53431. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  53432. }
  53433. // if the particles will always face the camera
  53434. if (this.billboard) {
  53435. // compute the camera position and un-rotate it by the current mesh rotation
  53436. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  53437. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  53438. this._cam_axisZ.normalize();
  53439. // same for camera up vector extracted from the cam view matrix
  53440. var view = this._camera.getViewMatrix(true);
  53441. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  53442. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  53443. this._cam_axisY.normalize();
  53444. this._cam_axisX.normalize();
  53445. }
  53446. // if depthSort, compute the camera global position in the mesh local system
  53447. if (this._depthSort) {
  53448. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  53449. }
  53450. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  53451. var idx = 0; // current position index in the global array positions32
  53452. var index = 0; // position start index in the global array positions32 of the current particle
  53453. var colidx = 0; // current color index in the global array colors32
  53454. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  53455. var uvidx = 0; // current uv index in the global array uvs32
  53456. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  53457. var pt = 0; // current index in the particle model shape
  53458. if (this.mesh.isFacetDataEnabled) {
  53459. this._computeBoundingBox = true;
  53460. }
  53461. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  53462. if (this._computeBoundingBox) {
  53463. if (start == 0 && end == this.nbParticles - 1) {
  53464. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  53465. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  53466. }
  53467. else {
  53468. if (this.mesh._boundingInfo) {
  53469. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  53470. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  53471. }
  53472. }
  53473. }
  53474. // particle loop
  53475. index = this.particles[start]._pos;
  53476. var vpos = (index / 3) | 0;
  53477. colorIndex = vpos * 4;
  53478. uvIndex = vpos * 2;
  53479. for (var p = start; p <= end; p++) {
  53480. this._particle = this.particles[p];
  53481. this._shape = this._particle._model._shape;
  53482. this._shapeUV = this._particle._model._shapeUV;
  53483. // call to custom user function to update the particle properties
  53484. this.updateParticle(this._particle);
  53485. // camera-particle distance for depth sorting
  53486. if (this._depthSort && this._depthSortParticles) {
  53487. var dsp = this.depthSortedParticles[p];
  53488. dsp.ind = this._particle._ind;
  53489. dsp.indicesLength = this._particle._model._indicesLength;
  53490. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  53491. }
  53492. // skip the computations for inactive or already invisible particles
  53493. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  53494. // increment indexes for the next particle
  53495. pt = this._shape.length;
  53496. index += pt * 3;
  53497. colorIndex += pt * 4;
  53498. uvIndex += pt * 2;
  53499. continue;
  53500. }
  53501. if (this._particle.isVisible) {
  53502. this._particle._stillInvisible = false; // un-mark permanent invisibility
  53503. this._particleHasParent = (this._particle.parentId !== null);
  53504. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  53505. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  53506. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  53507. // particle rotation matrix
  53508. if (this.billboard) {
  53509. this._particle.rotation.x = 0.0;
  53510. this._particle.rotation.y = 0.0;
  53511. }
  53512. if (this._computeParticleRotation || this.billboard) {
  53513. if (this._particle.rotationQuaternion) {
  53514. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  53515. }
  53516. else {
  53517. this._yaw = this._particle.rotation.y;
  53518. this._pitch = this._particle.rotation.x;
  53519. this._roll = this._particle.rotation.z;
  53520. this._quaternionRotationYPR();
  53521. }
  53522. this._quaternionToRotationMatrix();
  53523. }
  53524. if (this._particleHasParent) {
  53525. this._parent = this.particles[this._particle.parentId];
  53526. 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];
  53527. 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];
  53528. 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];
  53529. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  53530. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  53531. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  53532. if (this._computeParticleRotation || this.billboard) {
  53533. 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];
  53534. 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];
  53535. 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];
  53536. 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];
  53537. 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];
  53538. 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];
  53539. 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];
  53540. 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];
  53541. 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];
  53542. }
  53543. }
  53544. else {
  53545. this._particle._globalPosition.x = this._particle.position.x;
  53546. this._particle._globalPosition.y = this._particle.position.y;
  53547. this._particle._globalPosition.z = this._particle.position.z;
  53548. if (this._computeParticleRotation || this.billboard) {
  53549. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  53550. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  53551. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  53552. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  53553. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  53554. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  53555. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  53556. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  53557. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  53558. }
  53559. }
  53560. if (this._particle.translateFromPivot) {
  53561. this._pivotBackTranslation.x = 0.0;
  53562. this._pivotBackTranslation.y = 0.0;
  53563. this._pivotBackTranslation.z = 0.0;
  53564. }
  53565. else {
  53566. this._pivotBackTranslation.x = this._scaledPivot.x;
  53567. this._pivotBackTranslation.y = this._scaledPivot.y;
  53568. this._pivotBackTranslation.z = this._scaledPivot.z;
  53569. }
  53570. // particle vertex loop
  53571. for (pt = 0; pt < this._shape.length; pt++) {
  53572. idx = index + pt * 3;
  53573. colidx = colorIndex + pt * 4;
  53574. uvidx = uvIndex + pt * 2;
  53575. this._vertex.x = this._shape[pt].x;
  53576. this._vertex.y = this._shape[pt].y;
  53577. this._vertex.z = this._shape[pt].z;
  53578. if (this._computeParticleVertex) {
  53579. this.updateParticleVertex(this._particle, this._vertex, pt);
  53580. }
  53581. // positions
  53582. this._vertex.x *= this._particle.scaling.x;
  53583. this._vertex.y *= this._particle.scaling.y;
  53584. this._vertex.z *= this._particle.scaling.z;
  53585. this._vertex.x -= this._scaledPivot.x;
  53586. this._vertex.y -= this._scaledPivot.y;
  53587. this._vertex.z -= this._scaledPivot.z;
  53588. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  53589. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  53590. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  53591. this._rotated.x += this._pivotBackTranslation.x;
  53592. this._rotated.y += this._pivotBackTranslation.y;
  53593. this._rotated.z += this._pivotBackTranslation.z;
  53594. 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;
  53595. 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;
  53596. 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;
  53597. if (this._computeBoundingBox) {
  53598. if (this._positions32[idx] < this._minimum.x) {
  53599. this._minimum.x = this._positions32[idx];
  53600. }
  53601. if (this._positions32[idx] > this._maximum.x) {
  53602. this._maximum.x = this._positions32[idx];
  53603. }
  53604. if (this._positions32[idx + 1] < this._minimum.y) {
  53605. this._minimum.y = this._positions32[idx + 1];
  53606. }
  53607. if (this._positions32[idx + 1] > this._maximum.y) {
  53608. this._maximum.y = this._positions32[idx + 1];
  53609. }
  53610. if (this._positions32[idx + 2] < this._minimum.z) {
  53611. this._minimum.z = this._positions32[idx + 2];
  53612. }
  53613. if (this._positions32[idx + 2] > this._maximum.z) {
  53614. this._maximum.z = this._positions32[idx + 2];
  53615. }
  53616. }
  53617. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  53618. if (!this._computeParticleVertex) {
  53619. this._normal.x = this._fixedNormal32[idx];
  53620. this._normal.y = this._fixedNormal32[idx + 1];
  53621. this._normal.z = this._fixedNormal32[idx + 2];
  53622. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  53623. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  53624. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  53625. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  53626. 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;
  53627. 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;
  53628. }
  53629. if (this._computeParticleColor && this._particle.color) {
  53630. this._colors32[colidx] = this._particle.color.r;
  53631. this._colors32[colidx + 1] = this._particle.color.g;
  53632. this._colors32[colidx + 2] = this._particle.color.b;
  53633. this._colors32[colidx + 3] = this._particle.color.a;
  53634. }
  53635. if (this._computeParticleTexture) {
  53636. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53637. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53638. }
  53639. }
  53640. }
  53641. else {
  53642. this._particle._stillInvisible = true; // mark the particle as invisible
  53643. for (pt = 0; pt < this._shape.length; pt++) {
  53644. idx = index + pt * 3;
  53645. colidx = colorIndex + pt * 4;
  53646. uvidx = uvIndex + pt * 2;
  53647. this._positions32[idx] = 0.0;
  53648. this._positions32[idx + 1] = 0.0;
  53649. this._positions32[idx + 2] = 0.0;
  53650. this._normals32[idx] = 0.0;
  53651. this._normals32[idx + 1] = 0.0;
  53652. this._normals32[idx + 2] = 0.0;
  53653. if (this._computeParticleColor && this._particle.color) {
  53654. this._colors32[colidx] = this._particle.color.r;
  53655. this._colors32[colidx + 1] = this._particle.color.g;
  53656. this._colors32[colidx + 2] = this._particle.color.b;
  53657. this._colors32[colidx + 3] = this._particle.color.a;
  53658. }
  53659. if (this._computeParticleTexture) {
  53660. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53661. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53662. }
  53663. }
  53664. }
  53665. // if the particle intersections must be computed : update the bbInfo
  53666. if (this._particlesIntersect) {
  53667. var bInfo = this._particle._boundingInfo;
  53668. var bBox = bInfo.boundingBox;
  53669. var bSphere = bInfo.boundingSphere;
  53670. if (!this._bSphereOnly) {
  53671. // place, scale and rotate the particle bbox within the SPS local system, then update it
  53672. for (var b = 0; b < bBox.vectors.length; b++) {
  53673. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  53674. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  53675. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  53676. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  53677. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  53678. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  53679. 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;
  53680. 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;
  53681. 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;
  53682. }
  53683. bBox._update(this.mesh._worldMatrix);
  53684. }
  53685. // place and scale the particle bouding sphere in the SPS local system, then update it
  53686. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  53687. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  53688. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  53689. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  53690. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  53691. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  53692. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  53693. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  53694. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  53695. 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));
  53696. bSphere._update(this.mesh._worldMatrix);
  53697. }
  53698. // increment indexes for the next particle
  53699. index = idx + 3;
  53700. colorIndex = colidx + 4;
  53701. uvIndex = uvidx + 2;
  53702. }
  53703. // if the VBO must be updated
  53704. if (update) {
  53705. if (this._computeParticleColor) {
  53706. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  53707. }
  53708. if (this._computeParticleTexture) {
  53709. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  53710. }
  53711. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53712. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  53713. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  53714. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  53715. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  53716. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  53717. for (var i = 0; i < this._normals32.length; i++) {
  53718. this._fixedNormal32[i] = this._normals32[i];
  53719. }
  53720. }
  53721. if (!this.mesh.areNormalsFrozen) {
  53722. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  53723. }
  53724. }
  53725. if (this._depthSort && this._depthSortParticles) {
  53726. this.depthSortedParticles.sort(this._depthSortFunction);
  53727. var dspl = this.depthSortedParticles.length;
  53728. var sorted = 0;
  53729. var lind = 0;
  53730. var sind = 0;
  53731. var sid = 0;
  53732. for (sorted = 0; sorted < dspl; sorted++) {
  53733. lind = this.depthSortedParticles[sorted].indicesLength;
  53734. sind = this.depthSortedParticles[sorted].ind;
  53735. for (var i = 0; i < lind; i++) {
  53736. this._indices32[sid] = this._indices[sind + i];
  53737. sid++;
  53738. }
  53739. }
  53740. this.mesh.updateIndices(this._indices32);
  53741. }
  53742. }
  53743. if (this._computeBoundingBox) {
  53744. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  53745. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  53746. }
  53747. this.afterUpdateParticles(start, end, update);
  53748. return this;
  53749. };
  53750. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  53751. this._halfroll = this._roll * 0.5;
  53752. this._halfpitch = this._pitch * 0.5;
  53753. this._halfyaw = this._yaw * 0.5;
  53754. this._sinRoll = Math.sin(this._halfroll);
  53755. this._cosRoll = Math.cos(this._halfroll);
  53756. this._sinPitch = Math.sin(this._halfpitch);
  53757. this._cosPitch = Math.cos(this._halfpitch);
  53758. this._sinYaw = Math.sin(this._halfyaw);
  53759. this._cosYaw = Math.cos(this._halfyaw);
  53760. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  53761. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  53762. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  53763. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  53764. };
  53765. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  53766. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  53767. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  53768. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  53769. this._rotMatrix.m[3] = 0;
  53770. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  53771. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  53772. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  53773. this._rotMatrix.m[7] = 0;
  53774. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  53775. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  53776. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  53777. this._rotMatrix.m[11] = 0;
  53778. this._rotMatrix.m[12] = 0;
  53779. this._rotMatrix.m[13] = 0;
  53780. this._rotMatrix.m[14] = 0;
  53781. this._rotMatrix.m[15] = 1.0;
  53782. };
  53783. /**
  53784. * Disposes the SPS.
  53785. */
  53786. SolidParticleSystem.prototype.dispose = function () {
  53787. this.mesh.dispose();
  53788. this.vars = null;
  53789. // drop references to internal big arrays for the GC
  53790. this._positions = null;
  53791. this._indices = null;
  53792. this._normals = null;
  53793. this._uvs = null;
  53794. this._colors = null;
  53795. this._indices32 = null;
  53796. this._positions32 = null;
  53797. this._normals32 = null;
  53798. this._fixedNormal32 = null;
  53799. this._uvs32 = null;
  53800. this._colors32 = null;
  53801. this.pickedParticles = null;
  53802. };
  53803. /**
  53804. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  53805. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53806. * @returns the SPS.
  53807. */
  53808. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  53809. if (!this._isVisibilityBoxLocked) {
  53810. this.mesh.refreshBoundingInfo();
  53811. }
  53812. return this;
  53813. };
  53814. /**
  53815. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  53816. * @param size the size (float) of the visibility box
  53817. * note : this doesn't lock the SPS mesh bounding box.
  53818. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53819. */
  53820. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  53821. var vis = size / 2;
  53822. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  53823. };
  53824. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  53825. /**
  53826. * Gets whether the SPS as always visible or not
  53827. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53828. */
  53829. get: function () {
  53830. return this._alwaysVisible;
  53831. },
  53832. /**
  53833. * Sets the SPS as always visible or not
  53834. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53835. */
  53836. set: function (val) {
  53837. this._alwaysVisible = val;
  53838. this.mesh.alwaysSelectAsActiveMesh = val;
  53839. },
  53840. enumerable: true,
  53841. configurable: true
  53842. });
  53843. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  53844. /**
  53845. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  53846. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53847. */
  53848. get: function () {
  53849. return this._isVisibilityBoxLocked;
  53850. },
  53851. /**
  53852. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  53853. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53854. */
  53855. set: function (val) {
  53856. this._isVisibilityBoxLocked = val;
  53857. var boundingInfo = this.mesh.getBoundingInfo();
  53858. boundingInfo.isLocked = val;
  53859. },
  53860. enumerable: true,
  53861. configurable: true
  53862. });
  53863. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  53864. /**
  53865. * Gets if `setParticles()` computes the particle rotations or not.
  53866. * Default value : true. The SPS is faster when it's set to false.
  53867. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  53868. */
  53869. get: function () {
  53870. return this._computeParticleRotation;
  53871. },
  53872. /**
  53873. * Tells to `setParticles()` to compute the particle rotations or not.
  53874. * Default value : true. The SPS is faster when it's set to false.
  53875. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  53876. */
  53877. set: function (val) {
  53878. this._computeParticleRotation = val;
  53879. },
  53880. enumerable: true,
  53881. configurable: true
  53882. });
  53883. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  53884. /**
  53885. * Gets if `setParticles()` computes the particle colors or not.
  53886. * Default value : true. The SPS is faster when it's set to false.
  53887. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  53888. */
  53889. get: function () {
  53890. return this._computeParticleColor;
  53891. },
  53892. /**
  53893. * Tells to `setParticles()` to compute the particle colors or not.
  53894. * Default value : true. The SPS is faster when it's set to false.
  53895. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  53896. */
  53897. set: function (val) {
  53898. this._computeParticleColor = val;
  53899. },
  53900. enumerable: true,
  53901. configurable: true
  53902. });
  53903. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  53904. /**
  53905. * Gets if `setParticles()` computes the particle textures or not.
  53906. * Default value : true. The SPS is faster when it's set to false.
  53907. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  53908. */
  53909. get: function () {
  53910. return this._computeParticleTexture;
  53911. },
  53912. set: function (val) {
  53913. this._computeParticleTexture = val;
  53914. },
  53915. enumerable: true,
  53916. configurable: true
  53917. });
  53918. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  53919. /**
  53920. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  53921. * Default value : false. The SPS is faster when it's set to false.
  53922. * Note : the particle custom vertex positions aren't stored values.
  53923. */
  53924. get: function () {
  53925. return this._computeParticleVertex;
  53926. },
  53927. /**
  53928. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  53929. * Default value : false. The SPS is faster when it's set to false.
  53930. * Note : the particle custom vertex positions aren't stored values.
  53931. */
  53932. set: function (val) {
  53933. this._computeParticleVertex = val;
  53934. },
  53935. enumerable: true,
  53936. configurable: true
  53937. });
  53938. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  53939. /**
  53940. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  53941. */
  53942. get: function () {
  53943. return this._computeBoundingBox;
  53944. },
  53945. /**
  53946. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  53947. */
  53948. set: function (val) {
  53949. this._computeBoundingBox = val;
  53950. },
  53951. enumerable: true,
  53952. configurable: true
  53953. });
  53954. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  53955. /**
  53956. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  53957. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  53958. * Default : `true`
  53959. */
  53960. get: function () {
  53961. return this._depthSortParticles;
  53962. },
  53963. /**
  53964. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  53965. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  53966. * Default : `true`
  53967. */
  53968. set: function (val) {
  53969. this._depthSortParticles = val;
  53970. },
  53971. enumerable: true,
  53972. configurable: true
  53973. });
  53974. // =======================================================================
  53975. // Particle behavior logic
  53976. // these following methods may be overwritten by the user to fit his needs
  53977. /**
  53978. * This function does nothing. It may be overwritten to set all the particle first values.
  53979. * The SPS doesn't call this function, you may have to call it by your own.
  53980. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53981. */
  53982. SolidParticleSystem.prototype.initParticles = function () {
  53983. };
  53984. /**
  53985. * This function does nothing. It may be overwritten to recycle a particle.
  53986. * The SPS doesn't call this function, you may have to call it by your own.
  53987. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53988. * @param particle The particle to recycle
  53989. * @returns the recycled particle
  53990. */
  53991. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  53992. return particle;
  53993. };
  53994. /**
  53995. * Updates a particle : this function should be overwritten by the user.
  53996. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  53997. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53998. * @example : just set a particle position or velocity and recycle conditions
  53999. * @param particle The particle to update
  54000. * @returns the updated particle
  54001. */
  54002. SolidParticleSystem.prototype.updateParticle = function (particle) {
  54003. return particle;
  54004. };
  54005. /**
  54006. * Updates a vertex of a particle : it can be overwritten by the user.
  54007. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  54008. * @param particle the current particle
  54009. * @param vertex the current index of the current particle
  54010. * @param pt the index of the current vertex in the particle shape
  54011. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  54012. * @example : just set a vertex particle position
  54013. * @returns the updated vertex
  54014. */
  54015. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  54016. return vertex;
  54017. };
  54018. /**
  54019. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  54020. * This does nothing and may be overwritten by the user.
  54021. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54022. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54023. * @param update the boolean update value actually passed to setParticles()
  54024. */
  54025. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  54026. };
  54027. /**
  54028. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  54029. * This will be passed three parameters.
  54030. * This does nothing and may be overwritten by the user.
  54031. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54032. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54033. * @param update the boolean update value actually passed to setParticles()
  54034. */
  54035. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  54036. };
  54037. return SolidParticleSystem;
  54038. }());
  54039. BABYLON.SolidParticleSystem = SolidParticleSystem;
  54040. })(BABYLON || (BABYLON = {}));
  54041. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  54042. var BABYLON;
  54043. (function (BABYLON) {
  54044. var ShaderMaterial = /** @class */ (function (_super) {
  54045. __extends(ShaderMaterial, _super);
  54046. function ShaderMaterial(name, scene, shaderPath, options) {
  54047. var _this = _super.call(this, name, scene) || this;
  54048. _this._textures = {};
  54049. _this._textureArrays = {};
  54050. _this._floats = {};
  54051. _this._ints = {};
  54052. _this._floatsArrays = {};
  54053. _this._colors3 = {};
  54054. _this._colors3Arrays = {};
  54055. _this._colors4 = {};
  54056. _this._vectors2 = {};
  54057. _this._vectors3 = {};
  54058. _this._vectors4 = {};
  54059. _this._matrices = {};
  54060. _this._matrices3x3 = {};
  54061. _this._matrices2x2 = {};
  54062. _this._vectors2Arrays = {};
  54063. _this._vectors3Arrays = {};
  54064. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  54065. _this._shaderPath = shaderPath;
  54066. options.needAlphaBlending = options.needAlphaBlending || false;
  54067. options.needAlphaTesting = options.needAlphaTesting || false;
  54068. options.attributes = options.attributes || ["position", "normal", "uv"];
  54069. options.uniforms = options.uniforms || ["worldViewProjection"];
  54070. options.uniformBuffers = options.uniformBuffers || [];
  54071. options.samplers = options.samplers || [];
  54072. options.defines = options.defines || [];
  54073. _this._options = options;
  54074. return _this;
  54075. }
  54076. ShaderMaterial.prototype.getClassName = function () {
  54077. return "ShaderMaterial";
  54078. };
  54079. ShaderMaterial.prototype.needAlphaBlending = function () {
  54080. return this._options.needAlphaBlending;
  54081. };
  54082. ShaderMaterial.prototype.needAlphaTesting = function () {
  54083. return this._options.needAlphaTesting;
  54084. };
  54085. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  54086. if (this._options.uniforms.indexOf(uniformName) === -1) {
  54087. this._options.uniforms.push(uniformName);
  54088. }
  54089. };
  54090. ShaderMaterial.prototype.setTexture = function (name, texture) {
  54091. if (this._options.samplers.indexOf(name) === -1) {
  54092. this._options.samplers.push(name);
  54093. }
  54094. this._textures[name] = texture;
  54095. return this;
  54096. };
  54097. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  54098. if (this._options.samplers.indexOf(name) === -1) {
  54099. this._options.samplers.push(name);
  54100. }
  54101. this._checkUniform(name);
  54102. this._textureArrays[name] = textures;
  54103. return this;
  54104. };
  54105. ShaderMaterial.prototype.setFloat = function (name, value) {
  54106. this._checkUniform(name);
  54107. this._floats[name] = value;
  54108. return this;
  54109. };
  54110. ShaderMaterial.prototype.setInt = function (name, value) {
  54111. this._checkUniform(name);
  54112. this._ints[name] = value;
  54113. return this;
  54114. };
  54115. ShaderMaterial.prototype.setFloats = function (name, value) {
  54116. this._checkUniform(name);
  54117. this._floatsArrays[name] = value;
  54118. return this;
  54119. };
  54120. ShaderMaterial.prototype.setColor3 = function (name, value) {
  54121. this._checkUniform(name);
  54122. this._colors3[name] = value;
  54123. return this;
  54124. };
  54125. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  54126. this._checkUniform(name);
  54127. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  54128. color.toArray(arr, arr.length);
  54129. return arr;
  54130. }, []);
  54131. return this;
  54132. };
  54133. ShaderMaterial.prototype.setColor4 = function (name, value) {
  54134. this._checkUniform(name);
  54135. this._colors4[name] = value;
  54136. return this;
  54137. };
  54138. ShaderMaterial.prototype.setVector2 = function (name, value) {
  54139. this._checkUniform(name);
  54140. this._vectors2[name] = value;
  54141. return this;
  54142. };
  54143. ShaderMaterial.prototype.setVector3 = function (name, value) {
  54144. this._checkUniform(name);
  54145. this._vectors3[name] = value;
  54146. return this;
  54147. };
  54148. ShaderMaterial.prototype.setVector4 = function (name, value) {
  54149. this._checkUniform(name);
  54150. this._vectors4[name] = value;
  54151. return this;
  54152. };
  54153. ShaderMaterial.prototype.setMatrix = function (name, value) {
  54154. this._checkUniform(name);
  54155. this._matrices[name] = value;
  54156. return this;
  54157. };
  54158. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  54159. this._checkUniform(name);
  54160. this._matrices3x3[name] = value;
  54161. return this;
  54162. };
  54163. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  54164. this._checkUniform(name);
  54165. this._matrices2x2[name] = value;
  54166. return this;
  54167. };
  54168. ShaderMaterial.prototype.setArray2 = function (name, value) {
  54169. this._checkUniform(name);
  54170. this._vectors2Arrays[name] = value;
  54171. return this;
  54172. };
  54173. ShaderMaterial.prototype.setArray3 = function (name, value) {
  54174. this._checkUniform(name);
  54175. this._vectors3Arrays[name] = value;
  54176. return this;
  54177. };
  54178. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  54179. if (!mesh) {
  54180. return true;
  54181. }
  54182. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  54183. return false;
  54184. }
  54185. return false;
  54186. };
  54187. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  54188. var scene = this.getScene();
  54189. var engine = scene.getEngine();
  54190. if (!this.checkReadyOnEveryCall) {
  54191. if (this._renderId === scene.getRenderId()) {
  54192. if (this._checkCache(scene, mesh, useInstances)) {
  54193. return true;
  54194. }
  54195. }
  54196. }
  54197. // Instances
  54198. var defines = [];
  54199. var attribs = [];
  54200. var fallbacks = new BABYLON.EffectFallbacks();
  54201. if (useInstances) {
  54202. defines.push("#define INSTANCES");
  54203. }
  54204. for (var index = 0; index < this._options.defines.length; index++) {
  54205. defines.push(this._options.defines[index]);
  54206. }
  54207. for (var index = 0; index < this._options.attributes.length; index++) {
  54208. attribs.push(this._options.attributes[index]);
  54209. }
  54210. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  54211. attribs.push(BABYLON.VertexBuffer.ColorKind);
  54212. defines.push("#define VERTEXCOLOR");
  54213. }
  54214. // Bones
  54215. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  54216. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  54217. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  54218. if (mesh.numBoneInfluencers > 4) {
  54219. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  54220. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  54221. }
  54222. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  54223. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  54224. fallbacks.addCPUSkinningFallback(0, mesh);
  54225. if (this._options.uniforms.indexOf("mBones") === -1) {
  54226. this._options.uniforms.push("mBones");
  54227. }
  54228. }
  54229. else {
  54230. defines.push("#define NUM_BONE_INFLUENCERS 0");
  54231. }
  54232. // Textures
  54233. for (var name in this._textures) {
  54234. if (!this._textures[name].isReady()) {
  54235. return false;
  54236. }
  54237. }
  54238. // Alpha test
  54239. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  54240. defines.push("#define ALPHATEST");
  54241. }
  54242. var previousEffect = this._effect;
  54243. var join = defines.join("\n");
  54244. this._effect = engine.createEffect(this._shaderPath, {
  54245. attributes: attribs,
  54246. uniformsNames: this._options.uniforms,
  54247. uniformBuffersNames: this._options.uniformBuffers,
  54248. samplers: this._options.samplers,
  54249. defines: join,
  54250. fallbacks: fallbacks,
  54251. onCompiled: this.onCompiled,
  54252. onError: this.onError
  54253. }, engine);
  54254. if (!this._effect.isReady()) {
  54255. return false;
  54256. }
  54257. if (previousEffect !== this._effect) {
  54258. scene.resetCachedMaterial();
  54259. }
  54260. this._renderId = scene.getRenderId();
  54261. return true;
  54262. };
  54263. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  54264. var scene = this.getScene();
  54265. if (!this._effect) {
  54266. return;
  54267. }
  54268. if (this._options.uniforms.indexOf("world") !== -1) {
  54269. this._effect.setMatrix("world", world);
  54270. }
  54271. if (this._options.uniforms.indexOf("worldView") !== -1) {
  54272. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  54273. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  54274. }
  54275. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  54276. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  54277. }
  54278. };
  54279. ShaderMaterial.prototype.bind = function (world, mesh) {
  54280. // Std values
  54281. this.bindOnlyWorldMatrix(world);
  54282. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  54283. if (this._options.uniforms.indexOf("view") !== -1) {
  54284. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  54285. }
  54286. if (this._options.uniforms.indexOf("projection") !== -1) {
  54287. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  54288. }
  54289. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  54290. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  54291. }
  54292. // Bones
  54293. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  54294. var name;
  54295. // Texture
  54296. for (name in this._textures) {
  54297. this._effect.setTexture(name, this._textures[name]);
  54298. }
  54299. // Texture arrays
  54300. for (name in this._textureArrays) {
  54301. this._effect.setTextureArray(name, this._textureArrays[name]);
  54302. }
  54303. // Int
  54304. for (name in this._ints) {
  54305. this._effect.setInt(name, this._ints[name]);
  54306. }
  54307. // Float
  54308. for (name in this._floats) {
  54309. this._effect.setFloat(name, this._floats[name]);
  54310. }
  54311. // Floats
  54312. for (name in this._floatsArrays) {
  54313. this._effect.setArray(name, this._floatsArrays[name]);
  54314. }
  54315. // Color3
  54316. for (name in this._colors3) {
  54317. this._effect.setColor3(name, this._colors3[name]);
  54318. }
  54319. for (name in this._colors3Arrays) {
  54320. this._effect.setArray3(name, this._colors3Arrays[name]);
  54321. }
  54322. // Color4
  54323. for (name in this._colors4) {
  54324. var color = this._colors4[name];
  54325. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  54326. }
  54327. // Vector2
  54328. for (name in this._vectors2) {
  54329. this._effect.setVector2(name, this._vectors2[name]);
  54330. }
  54331. // Vector3
  54332. for (name in this._vectors3) {
  54333. this._effect.setVector3(name, this._vectors3[name]);
  54334. }
  54335. // Vector4
  54336. for (name in this._vectors4) {
  54337. this._effect.setVector4(name, this._vectors4[name]);
  54338. }
  54339. // Matrix
  54340. for (name in this._matrices) {
  54341. this._effect.setMatrix(name, this._matrices[name]);
  54342. }
  54343. // Matrix 3x3
  54344. for (name in this._matrices3x3) {
  54345. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  54346. }
  54347. // Matrix 2x2
  54348. for (name in this._matrices2x2) {
  54349. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  54350. }
  54351. // Vector2Array
  54352. for (name in this._vectors2Arrays) {
  54353. this._effect.setArray2(name, this._vectors2Arrays[name]);
  54354. }
  54355. // Vector3Array
  54356. for (name in this._vectors3Arrays) {
  54357. this._effect.setArray3(name, this._vectors3Arrays[name]);
  54358. }
  54359. }
  54360. this._afterBind(mesh);
  54361. };
  54362. ShaderMaterial.prototype.getActiveTextures = function () {
  54363. var activeTextures = _super.prototype.getActiveTextures.call(this);
  54364. for (var name in this._textures) {
  54365. activeTextures.push(this._textures[name]);
  54366. }
  54367. for (var name in this._textureArrays) {
  54368. var array = this._textureArrays[name];
  54369. for (var index = 0; index < array.length; index++) {
  54370. activeTextures.push(array[index]);
  54371. }
  54372. }
  54373. return activeTextures;
  54374. };
  54375. ShaderMaterial.prototype.hasTexture = function (texture) {
  54376. if (_super.prototype.hasTexture.call(this, texture)) {
  54377. return true;
  54378. }
  54379. for (var name in this._textures) {
  54380. if (this._textures[name] === texture) {
  54381. return true;
  54382. }
  54383. }
  54384. for (var name in this._textureArrays) {
  54385. var array = this._textureArrays[name];
  54386. for (var index = 0; index < array.length; index++) {
  54387. if (array[index] === texture) {
  54388. return true;
  54389. }
  54390. }
  54391. }
  54392. return false;
  54393. };
  54394. ShaderMaterial.prototype.clone = function (name) {
  54395. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  54396. return newShaderMaterial;
  54397. };
  54398. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  54399. if (forceDisposeTextures) {
  54400. var name;
  54401. for (name in this._textures) {
  54402. this._textures[name].dispose();
  54403. }
  54404. for (name in this._textureArrays) {
  54405. var array = this._textureArrays[name];
  54406. for (var index = 0; index < array.length; index++) {
  54407. array[index].dispose();
  54408. }
  54409. }
  54410. }
  54411. this._textures = {};
  54412. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  54413. };
  54414. ShaderMaterial.prototype.serialize = function () {
  54415. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  54416. serializationObject.customType = "BABYLON.ShaderMaterial";
  54417. serializationObject.options = this._options;
  54418. serializationObject.shaderPath = this._shaderPath;
  54419. var name;
  54420. // Texture
  54421. serializationObject.textures = {};
  54422. for (name in this._textures) {
  54423. serializationObject.textures[name] = this._textures[name].serialize();
  54424. }
  54425. // Texture arrays
  54426. serializationObject.textureArrays = {};
  54427. for (name in this._textureArrays) {
  54428. serializationObject.textureArrays[name] = [];
  54429. var array = this._textureArrays[name];
  54430. for (var index = 0; index < array.length; index++) {
  54431. serializationObject.textureArrays[name].push(array[index].serialize());
  54432. }
  54433. }
  54434. // Float
  54435. serializationObject.floats = {};
  54436. for (name in this._floats) {
  54437. serializationObject.floats[name] = this._floats[name];
  54438. }
  54439. // Float s
  54440. serializationObject.FloatArrays = {};
  54441. for (name in this._floatsArrays) {
  54442. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  54443. }
  54444. // Color3
  54445. serializationObject.colors3 = {};
  54446. for (name in this._colors3) {
  54447. serializationObject.colors3[name] = this._colors3[name].asArray();
  54448. }
  54449. // Color3 array
  54450. serializationObject.colors3Arrays = {};
  54451. for (name in this._colors3Arrays) {
  54452. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  54453. }
  54454. // Color4
  54455. serializationObject.colors4 = {};
  54456. for (name in this._colors4) {
  54457. serializationObject.colors4[name] = this._colors4[name].asArray();
  54458. }
  54459. // Vector2
  54460. serializationObject.vectors2 = {};
  54461. for (name in this._vectors2) {
  54462. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  54463. }
  54464. // Vector3
  54465. serializationObject.vectors3 = {};
  54466. for (name in this._vectors3) {
  54467. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  54468. }
  54469. // Vector4
  54470. serializationObject.vectors4 = {};
  54471. for (name in this._vectors4) {
  54472. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  54473. }
  54474. // Matrix
  54475. serializationObject.matrices = {};
  54476. for (name in this._matrices) {
  54477. serializationObject.matrices[name] = this._matrices[name].asArray();
  54478. }
  54479. // Matrix 3x3
  54480. serializationObject.matrices3x3 = {};
  54481. for (name in this._matrices3x3) {
  54482. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  54483. }
  54484. // Matrix 2x2
  54485. serializationObject.matrices2x2 = {};
  54486. for (name in this._matrices2x2) {
  54487. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  54488. }
  54489. // Vector2Array
  54490. serializationObject.vectors2Arrays = {};
  54491. for (name in this._vectors2Arrays) {
  54492. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  54493. }
  54494. // Vector3Array
  54495. serializationObject.vectors3Arrays = {};
  54496. for (name in this._vectors3Arrays) {
  54497. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  54498. }
  54499. return serializationObject;
  54500. };
  54501. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  54502. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  54503. var name;
  54504. // Texture
  54505. for (name in source.textures) {
  54506. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  54507. }
  54508. // Texture arrays
  54509. for (name in source.textureArrays) {
  54510. var array = source.textureArrays[name];
  54511. var textureArray = new Array();
  54512. for (var index = 0; index < array.length; index++) {
  54513. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  54514. }
  54515. material.setTextureArray(name, textureArray);
  54516. }
  54517. // Float
  54518. for (name in source.floats) {
  54519. material.setFloat(name, source.floats[name]);
  54520. }
  54521. // Float s
  54522. for (name in source.floatsArrays) {
  54523. material.setFloats(name, source.floatsArrays[name]);
  54524. }
  54525. // Color3
  54526. for (name in source.colors3) {
  54527. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  54528. }
  54529. // Color3 arrays
  54530. for (name in source.colors3Arrays) {
  54531. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  54532. if (i % 3 === 0) {
  54533. arr.push([num]);
  54534. }
  54535. else {
  54536. arr[arr.length - 1].push(num);
  54537. }
  54538. return arr;
  54539. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  54540. material.setColor3Array(name, colors);
  54541. }
  54542. // Color4
  54543. for (name in source.colors4) {
  54544. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  54545. }
  54546. // Vector2
  54547. for (name in source.vectors2) {
  54548. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  54549. }
  54550. // Vector3
  54551. for (name in source.vectors3) {
  54552. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  54553. }
  54554. // Vector4
  54555. for (name in source.vectors4) {
  54556. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  54557. }
  54558. // Matrix
  54559. for (name in source.matrices) {
  54560. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  54561. }
  54562. // Matrix 3x3
  54563. for (name in source.matrices3x3) {
  54564. material.setMatrix3x3(name, source.matrices3x3[name]);
  54565. }
  54566. // Matrix 2x2
  54567. for (name in source.matrices2x2) {
  54568. material.setMatrix2x2(name, source.matrices2x2[name]);
  54569. }
  54570. // Vector2Array
  54571. for (name in source.vectors2Arrays) {
  54572. material.setArray2(name, source.vectors2Arrays[name]);
  54573. }
  54574. // Vector3Array
  54575. for (name in source.vectors3Arrays) {
  54576. material.setArray3(name, source.vectors3Arrays[name]);
  54577. }
  54578. return material;
  54579. };
  54580. return ShaderMaterial;
  54581. }(BABYLON.Material));
  54582. BABYLON.ShaderMaterial = ShaderMaterial;
  54583. })(BABYLON || (BABYLON = {}));
  54584. //# sourceMappingURL=babylon.shaderMaterial.js.map
  54585. var BABYLON;
  54586. (function (BABYLON) {
  54587. var GroundMesh = /** @class */ (function (_super) {
  54588. __extends(GroundMesh, _super);
  54589. function GroundMesh(name, scene) {
  54590. var _this = _super.call(this, name, scene) || this;
  54591. _this.generateOctree = false;
  54592. return _this;
  54593. }
  54594. GroundMesh.prototype.getClassName = function () {
  54595. return "GroundMesh";
  54596. };
  54597. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  54598. get: function () {
  54599. return Math.min(this._subdivisionsX, this._subdivisionsY);
  54600. },
  54601. enumerable: true,
  54602. configurable: true
  54603. });
  54604. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  54605. get: function () {
  54606. return this._subdivisionsX;
  54607. },
  54608. enumerable: true,
  54609. configurable: true
  54610. });
  54611. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  54612. get: function () {
  54613. return this._subdivisionsY;
  54614. },
  54615. enumerable: true,
  54616. configurable: true
  54617. });
  54618. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  54619. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  54620. this._subdivisionsX = chunksCount;
  54621. this._subdivisionsY = chunksCount;
  54622. this.subdivide(chunksCount);
  54623. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  54624. };
  54625. /**
  54626. * Returns a height (y) value in the Worl system :
  54627. * the ground altitude at the coordinates (x, z) expressed in the World system.
  54628. * Returns the ground y position if (x, z) are outside the ground surface.
  54629. */
  54630. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  54631. var world = this.getWorldMatrix();
  54632. var invMat = BABYLON.Tmp.Matrix[5];
  54633. world.invertToRef(invMat);
  54634. var tmpVect = BABYLON.Tmp.Vector3[8];
  54635. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  54636. x = tmpVect.x;
  54637. z = tmpVect.z;
  54638. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  54639. return this.position.y;
  54640. }
  54641. if (!this._heightQuads || this._heightQuads.length == 0) {
  54642. this._initHeightQuads();
  54643. this._computeHeightQuads();
  54644. }
  54645. var facet = this._getFacetAt(x, z);
  54646. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  54647. // return y in the World system
  54648. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  54649. return tmpVect.y;
  54650. };
  54651. /**
  54652. * Returns a normalized vector (Vector3) orthogonal to the ground
  54653. * at the ground coordinates (x, z) expressed in the World system.
  54654. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  54655. */
  54656. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  54657. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  54658. this.getNormalAtCoordinatesToRef(x, z, normal);
  54659. return normal;
  54660. };
  54661. /**
  54662. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  54663. * at the ground coordinates (x, z) expressed in the World system.
  54664. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  54665. * Returns the GroundMesh.
  54666. */
  54667. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  54668. var world = this.getWorldMatrix();
  54669. var tmpMat = BABYLON.Tmp.Matrix[5];
  54670. world.invertToRef(tmpMat);
  54671. var tmpVect = BABYLON.Tmp.Vector3[8];
  54672. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  54673. x = tmpVect.x;
  54674. z = tmpVect.z;
  54675. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  54676. return this;
  54677. }
  54678. if (!this._heightQuads || this._heightQuads.length == 0) {
  54679. this._initHeightQuads();
  54680. this._computeHeightQuads();
  54681. }
  54682. var facet = this._getFacetAt(x, z);
  54683. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  54684. return this;
  54685. };
  54686. /**
  54687. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  54688. * if the ground has been updated.
  54689. * This can be used in the render loop.
  54690. * Returns the GroundMesh.
  54691. */
  54692. GroundMesh.prototype.updateCoordinateHeights = function () {
  54693. if (!this._heightQuads || this._heightQuads.length == 0) {
  54694. this._initHeightQuads();
  54695. }
  54696. this._computeHeightQuads();
  54697. return this;
  54698. };
  54699. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  54700. GroundMesh.prototype._getFacetAt = function (x, z) {
  54701. // retrieve col and row from x, z coordinates in the ground local system
  54702. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  54703. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  54704. var quad = this._heightQuads[row * this._subdivisionsX + col];
  54705. var facet;
  54706. if (z < quad.slope.x * x + quad.slope.y) {
  54707. facet = quad.facet1;
  54708. }
  54709. else {
  54710. facet = quad.facet2;
  54711. }
  54712. return facet;
  54713. };
  54714. // Creates and populates the heightMap array with "facet" elements :
  54715. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  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._initHeightQuads = function () {
  54721. var subdivisionsX = this._subdivisionsX;
  54722. var subdivisionsY = this._subdivisionsY;
  54723. this._heightQuads = new Array();
  54724. for (var row = 0; row < subdivisionsY; row++) {
  54725. for (var col = 0; col < subdivisionsX; col++) {
  54726. 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) };
  54727. this._heightQuads[row * subdivisionsX + col] = quad;
  54728. }
  54729. }
  54730. return this;
  54731. };
  54732. // Compute each quad element values and update the the heightMap array :
  54733. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  54734. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  54735. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  54736. // Returns the GroundMesh.
  54737. GroundMesh.prototype._computeHeightQuads = function () {
  54738. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54739. if (!positions) {
  54740. return this;
  54741. }
  54742. var v1 = BABYLON.Tmp.Vector3[3];
  54743. var v2 = BABYLON.Tmp.Vector3[2];
  54744. var v3 = BABYLON.Tmp.Vector3[1];
  54745. var v4 = BABYLON.Tmp.Vector3[0];
  54746. var v1v2 = BABYLON.Tmp.Vector3[4];
  54747. var v1v3 = BABYLON.Tmp.Vector3[5];
  54748. var v1v4 = BABYLON.Tmp.Vector3[6];
  54749. var norm1 = BABYLON.Tmp.Vector3[7];
  54750. var norm2 = BABYLON.Tmp.Vector3[8];
  54751. var i = 0;
  54752. var j = 0;
  54753. var k = 0;
  54754. var cd = 0; // 2D slope coefficient : z = cd * x + h
  54755. var h = 0;
  54756. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  54757. var d2 = 0;
  54758. var subdivisionsX = this._subdivisionsX;
  54759. var subdivisionsY = this._subdivisionsY;
  54760. for (var row = 0; row < subdivisionsY; row++) {
  54761. for (var col = 0; col < subdivisionsX; col++) {
  54762. i = col * 3;
  54763. j = row * (subdivisionsX + 1) * 3;
  54764. k = (row + 1) * (subdivisionsX + 1) * 3;
  54765. v1.x = positions[j + i];
  54766. v1.y = positions[j + i + 1];
  54767. v1.z = positions[j + i + 2];
  54768. v2.x = positions[j + i + 3];
  54769. v2.y = positions[j + i + 4];
  54770. v2.z = positions[j + i + 5];
  54771. v3.x = positions[k + i];
  54772. v3.y = positions[k + i + 1];
  54773. v3.z = positions[k + i + 2];
  54774. v4.x = positions[k + i + 3];
  54775. v4.y = positions[k + i + 4];
  54776. v4.z = positions[k + i + 5];
  54777. // 2D slope V1V4
  54778. cd = (v4.z - v1.z) / (v4.x - v1.x);
  54779. h = v1.z - cd * v1.x; // v1 belongs to the slope
  54780. // facet equations :
  54781. // we compute each facet normal vector
  54782. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  54783. // we compute the value d by applying the equation to v1 which belongs to the plane
  54784. // then we store the facet equation in a Vector4
  54785. v2.subtractToRef(v1, v1v2);
  54786. v3.subtractToRef(v1, v1v3);
  54787. v4.subtractToRef(v1, v1v4);
  54788. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  54789. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  54790. norm1.normalize();
  54791. norm2.normalize();
  54792. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  54793. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  54794. var quad = this._heightQuads[row * subdivisionsX + col];
  54795. quad.slope.copyFromFloats(cd, h);
  54796. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  54797. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  54798. }
  54799. }
  54800. return this;
  54801. };
  54802. GroundMesh.prototype.serialize = function (serializationObject) {
  54803. _super.prototype.serialize.call(this, serializationObject);
  54804. serializationObject.subdivisionsX = this._subdivisionsX;
  54805. serializationObject.subdivisionsY = this._subdivisionsY;
  54806. serializationObject.minX = this._minX;
  54807. serializationObject.maxX = this._maxX;
  54808. serializationObject.minZ = this._minZ;
  54809. serializationObject.maxZ = this._maxZ;
  54810. serializationObject.width = this._width;
  54811. serializationObject.height = this._height;
  54812. };
  54813. GroundMesh.Parse = function (parsedMesh, scene) {
  54814. var result = new GroundMesh(parsedMesh.name, scene);
  54815. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  54816. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  54817. result._minX = parsedMesh.minX;
  54818. result._maxX = parsedMesh.maxX;
  54819. result._minZ = parsedMesh.minZ;
  54820. result._maxZ = parsedMesh.maxZ;
  54821. result._width = parsedMesh.width;
  54822. result._height = parsedMesh.height;
  54823. return result;
  54824. };
  54825. return GroundMesh;
  54826. }(BABYLON.Mesh));
  54827. BABYLON.GroundMesh = GroundMesh;
  54828. })(BABYLON || (BABYLON = {}));
  54829. //# sourceMappingURL=babylon.groundMesh.js.map
  54830. var BABYLON;
  54831. (function (BABYLON) {
  54832. /**
  54833. * Creates an instance based on a source mesh.
  54834. */
  54835. var InstancedMesh = /** @class */ (function (_super) {
  54836. __extends(InstancedMesh, _super);
  54837. function InstancedMesh(name, source) {
  54838. var _this = _super.call(this, name, source.getScene()) || this;
  54839. source.instances.push(_this);
  54840. _this._sourceMesh = source;
  54841. _this.position.copyFrom(source.position);
  54842. _this.rotation.copyFrom(source.rotation);
  54843. _this.scaling.copyFrom(source.scaling);
  54844. if (source.rotationQuaternion) {
  54845. _this.rotationQuaternion = source.rotationQuaternion.clone();
  54846. }
  54847. _this.infiniteDistance = source.infiniteDistance;
  54848. _this.setPivotMatrix(source.getPivotMatrix());
  54849. _this.refreshBoundingInfo();
  54850. _this._syncSubMeshes();
  54851. return _this;
  54852. }
  54853. /**
  54854. * Returns the string "InstancedMesh".
  54855. */
  54856. InstancedMesh.prototype.getClassName = function () {
  54857. return "InstancedMesh";
  54858. };
  54859. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  54860. // Methods
  54861. get: function () {
  54862. return this._sourceMesh.receiveShadows;
  54863. },
  54864. enumerable: true,
  54865. configurable: true
  54866. });
  54867. Object.defineProperty(InstancedMesh.prototype, "material", {
  54868. get: function () {
  54869. return this._sourceMesh.material;
  54870. },
  54871. enumerable: true,
  54872. configurable: true
  54873. });
  54874. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  54875. get: function () {
  54876. return this._sourceMesh.visibility;
  54877. },
  54878. enumerable: true,
  54879. configurable: true
  54880. });
  54881. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  54882. get: function () {
  54883. return this._sourceMesh.skeleton;
  54884. },
  54885. enumerable: true,
  54886. configurable: true
  54887. });
  54888. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  54889. get: function () {
  54890. return this._sourceMesh.renderingGroupId;
  54891. },
  54892. enumerable: true,
  54893. configurable: true
  54894. });
  54895. /**
  54896. * Returns the total number of vertices (integer).
  54897. */
  54898. InstancedMesh.prototype.getTotalVertices = function () {
  54899. return this._sourceMesh.getTotalVertices();
  54900. };
  54901. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  54902. get: function () {
  54903. return this._sourceMesh;
  54904. },
  54905. enumerable: true,
  54906. configurable: true
  54907. });
  54908. /**
  54909. * Is this node ready to be used/rendered
  54910. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  54911. * @return {boolean} is it ready
  54912. */
  54913. InstancedMesh.prototype.isReady = function (completeCheck) {
  54914. if (completeCheck === void 0) { completeCheck = false; }
  54915. return this._sourceMesh.isReady(completeCheck, true);
  54916. };
  54917. /**
  54918. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  54919. */
  54920. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  54921. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  54922. };
  54923. /**
  54924. * Sets the vertex data of the mesh geometry for the requested `kind`.
  54925. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  54926. * The `data` are either a numeric array either a Float32Array.
  54927. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  54928. * 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).
  54929. * Note that a new underlying VertexBuffer object is created each call.
  54930. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  54931. *
  54932. * Possible `kind` values :
  54933. * - BABYLON.VertexBuffer.PositionKind
  54934. * - BABYLON.VertexBuffer.UVKind
  54935. * - BABYLON.VertexBuffer.UV2Kind
  54936. * - BABYLON.VertexBuffer.UV3Kind
  54937. * - BABYLON.VertexBuffer.UV4Kind
  54938. * - BABYLON.VertexBuffer.UV5Kind
  54939. * - BABYLON.VertexBuffer.UV6Kind
  54940. * - BABYLON.VertexBuffer.ColorKind
  54941. * - BABYLON.VertexBuffer.MatricesIndicesKind
  54942. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  54943. * - BABYLON.VertexBuffer.MatricesWeightsKind
  54944. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  54945. *
  54946. * Returns the Mesh.
  54947. */
  54948. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  54949. if (this.sourceMesh) {
  54950. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  54951. }
  54952. return this.sourceMesh;
  54953. };
  54954. /**
  54955. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  54956. * If the mesh has no geometry, it is simply returned as it is.
  54957. * The `data` are either a numeric array either a Float32Array.
  54958. * No new underlying VertexBuffer object is created.
  54959. * 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.
  54960. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  54961. *
  54962. * Possible `kind` values :
  54963. * - BABYLON.VertexBuffer.PositionKind
  54964. * - BABYLON.VertexBuffer.UVKind
  54965. * - BABYLON.VertexBuffer.UV2Kind
  54966. * - BABYLON.VertexBuffer.UV3Kind
  54967. * - BABYLON.VertexBuffer.UV4Kind
  54968. * - BABYLON.VertexBuffer.UV5Kind
  54969. * - BABYLON.VertexBuffer.UV6Kind
  54970. * - BABYLON.VertexBuffer.ColorKind
  54971. * - BABYLON.VertexBuffer.MatricesIndicesKind
  54972. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  54973. * - BABYLON.VertexBuffer.MatricesWeightsKind
  54974. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  54975. *
  54976. * Returns the Mesh.
  54977. */
  54978. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  54979. if (this.sourceMesh) {
  54980. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  54981. }
  54982. return this.sourceMesh;
  54983. };
  54984. /**
  54985. * Sets the mesh indices.
  54986. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  54987. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  54988. * This method creates a new index buffer each call.
  54989. * Returns the Mesh.
  54990. */
  54991. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  54992. if (totalVertices === void 0) { totalVertices = null; }
  54993. if (this.sourceMesh) {
  54994. this.sourceMesh.setIndices(indices, totalVertices);
  54995. }
  54996. return this.sourceMesh;
  54997. };
  54998. /**
  54999. * Boolean : True if the mesh owns the requested kind of data.
  55000. */
  55001. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  55002. return this._sourceMesh.isVerticesDataPresent(kind);
  55003. };
  55004. /**
  55005. * Returns an array of indices (IndicesArray).
  55006. */
  55007. InstancedMesh.prototype.getIndices = function () {
  55008. return this._sourceMesh.getIndices();
  55009. };
  55010. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  55011. get: function () {
  55012. return this._sourceMesh._positions;
  55013. },
  55014. enumerable: true,
  55015. configurable: true
  55016. });
  55017. /**
  55018. * Sets a new updated BoundingInfo to the mesh.
  55019. * Returns the mesh.
  55020. */
  55021. InstancedMesh.prototype.refreshBoundingInfo = function () {
  55022. var meshBB = this._sourceMesh.getBoundingInfo();
  55023. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  55024. this._updateBoundingInfo();
  55025. return this;
  55026. };
  55027. InstancedMesh.prototype._preActivate = function () {
  55028. if (this._currentLOD) {
  55029. this._currentLOD._preActivate();
  55030. }
  55031. return this;
  55032. };
  55033. InstancedMesh.prototype._activate = function (renderId) {
  55034. if (this._currentLOD) {
  55035. this._currentLOD._registerInstanceForRenderId(this, renderId);
  55036. }
  55037. return this;
  55038. };
  55039. /**
  55040. * Returns the current associated LOD AbstractMesh.
  55041. */
  55042. InstancedMesh.prototype.getLOD = function (camera) {
  55043. if (!camera) {
  55044. return this;
  55045. }
  55046. var boundingInfo = this.getBoundingInfo();
  55047. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  55048. if (this._currentLOD === this.sourceMesh) {
  55049. return this;
  55050. }
  55051. return this._currentLOD;
  55052. };
  55053. InstancedMesh.prototype._syncSubMeshes = function () {
  55054. this.releaseSubMeshes();
  55055. if (this._sourceMesh.subMeshes) {
  55056. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  55057. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  55058. }
  55059. }
  55060. return this;
  55061. };
  55062. InstancedMesh.prototype._generatePointsArray = function () {
  55063. return this._sourceMesh._generatePointsArray();
  55064. };
  55065. /**
  55066. * Creates a new InstancedMesh from the current mesh.
  55067. * - name (string) : the cloned mesh name
  55068. * - newParent (optional Node) : the optional Node to parent the clone to.
  55069. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  55070. *
  55071. * Returns the clone.
  55072. */
  55073. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  55074. var result = this._sourceMesh.createInstance(name);
  55075. // Deep copy
  55076. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  55077. // Bounding info
  55078. this.refreshBoundingInfo();
  55079. // Parent
  55080. if (newParent) {
  55081. result.parent = newParent;
  55082. }
  55083. if (!doNotCloneChildren) {
  55084. // Children
  55085. for (var index = 0; index < this.getScene().meshes.length; index++) {
  55086. var mesh = this.getScene().meshes[index];
  55087. if (mesh.parent === this) {
  55088. mesh.clone(mesh.name, result);
  55089. }
  55090. }
  55091. }
  55092. result.computeWorldMatrix(true);
  55093. return result;
  55094. };
  55095. /**
  55096. * Disposes the InstancedMesh.
  55097. * Returns nothing.
  55098. */
  55099. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  55100. // Remove from mesh
  55101. var index = this._sourceMesh.instances.indexOf(this);
  55102. this._sourceMesh.instances.splice(index, 1);
  55103. _super.prototype.dispose.call(this, doNotRecurse);
  55104. };
  55105. return InstancedMesh;
  55106. }(BABYLON.AbstractMesh));
  55107. BABYLON.InstancedMesh = InstancedMesh;
  55108. })(BABYLON || (BABYLON = {}));
  55109. //# sourceMappingURL=babylon.instancedMesh.js.map
  55110. var BABYLON;
  55111. (function (BABYLON) {
  55112. var LinesMesh = /** @class */ (function (_super) {
  55113. __extends(LinesMesh, _super);
  55114. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  55115. if (scene === void 0) { scene = null; }
  55116. if (parent === void 0) { parent = null; }
  55117. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  55118. _this.useVertexColor = useVertexColor;
  55119. _this.useVertexAlpha = useVertexAlpha;
  55120. _this.color = new BABYLON.Color3(1, 1, 1);
  55121. _this.alpha = 1;
  55122. if (source) {
  55123. _this.color = source.color.clone();
  55124. _this.alpha = source.alpha;
  55125. _this.useVertexColor = source.useVertexColor;
  55126. _this.useVertexAlpha = source.useVertexAlpha;
  55127. }
  55128. _this._intersectionThreshold = 0.1;
  55129. var defines = [];
  55130. var options = {
  55131. attributes: [BABYLON.VertexBuffer.PositionKind],
  55132. uniforms: ["world", "viewProjection"],
  55133. needAlphaBlending: true,
  55134. defines: defines
  55135. };
  55136. if (useVertexAlpha === false) {
  55137. options.needAlphaBlending = false;
  55138. }
  55139. if (!useVertexColor) {
  55140. options.uniforms.push("color");
  55141. }
  55142. else {
  55143. options.defines.push("#define VERTEXCOLOR");
  55144. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  55145. }
  55146. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  55147. return _this;
  55148. }
  55149. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  55150. /**
  55151. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  55152. * This margin is expressed in world space coordinates, so its value may vary.
  55153. * Default value is 0.1
  55154. * @returns the intersection Threshold value.
  55155. */
  55156. get: function () {
  55157. return this._intersectionThreshold;
  55158. },
  55159. /**
  55160. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  55161. * This margin is expressed in world space coordinates, so its value may vary.
  55162. * @param value the new threshold to apply
  55163. */
  55164. set: function (value) {
  55165. if (this._intersectionThreshold === value) {
  55166. return;
  55167. }
  55168. this._intersectionThreshold = value;
  55169. if (this.geometry) {
  55170. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  55171. }
  55172. },
  55173. enumerable: true,
  55174. configurable: true
  55175. });
  55176. /**
  55177. * Returns the string "LineMesh"
  55178. */
  55179. LinesMesh.prototype.getClassName = function () {
  55180. return "LinesMesh";
  55181. };
  55182. Object.defineProperty(LinesMesh.prototype, "material", {
  55183. get: function () {
  55184. return this._colorShader;
  55185. },
  55186. set: function (value) {
  55187. // Do nothing
  55188. },
  55189. enumerable: true,
  55190. configurable: true
  55191. });
  55192. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  55193. get: function () {
  55194. return false;
  55195. },
  55196. enumerable: true,
  55197. configurable: true
  55198. });
  55199. LinesMesh.prototype.createInstance = function (name) {
  55200. throw new Error("LinesMeshes do not support createInstance.");
  55201. };
  55202. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  55203. if (!this._geometry) {
  55204. return this;
  55205. }
  55206. // VBOs
  55207. this._geometry._bind(this._colorShader.getEffect());
  55208. // Color
  55209. if (!this.useVertexColor) {
  55210. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  55211. }
  55212. return this;
  55213. };
  55214. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  55215. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  55216. return this;
  55217. }
  55218. var engine = this.getScene().getEngine();
  55219. // Draw order
  55220. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  55221. return this;
  55222. };
  55223. LinesMesh.prototype.dispose = function (doNotRecurse) {
  55224. this._colorShader.dispose();
  55225. _super.prototype.dispose.call(this, doNotRecurse);
  55226. };
  55227. /**
  55228. * Returns a new LineMesh object cloned from the current one.
  55229. */
  55230. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  55231. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  55232. };
  55233. return LinesMesh;
  55234. }(BABYLON.Mesh));
  55235. BABYLON.LinesMesh = LinesMesh;
  55236. })(BABYLON || (BABYLON = {}));
  55237. //# sourceMappingURL=babylon.linesMesh.js.map
  55238. var BABYLON;
  55239. (function (BABYLON) {
  55240. var MeshBuilder = /** @class */ (function () {
  55241. function MeshBuilder() {
  55242. }
  55243. MeshBuilder.updateSideOrientation = function (orientation) {
  55244. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  55245. return BABYLON.Mesh.DOUBLESIDE;
  55246. }
  55247. if (orientation === undefined || orientation === null) {
  55248. return BABYLON.Mesh.FRONTSIDE;
  55249. }
  55250. return orientation;
  55251. };
  55252. /**
  55253. * Creates a box mesh.
  55254. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  55255. * The parameter `size` sets the size (float) of each box side (default 1).
  55256. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  55257. * 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).
  55258. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  55259. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55260. * 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).
  55261. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55262. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55263. */
  55264. MeshBuilder.CreateBox = function (name, options, scene) {
  55265. if (scene === void 0) { scene = null; }
  55266. var box = new BABYLON.Mesh(name, scene);
  55267. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55268. box._originalBuilderSideOrientation = options.sideOrientation;
  55269. var vertexData = BABYLON.VertexData.CreateBox(options);
  55270. vertexData.applyToMesh(box, options.updatable);
  55271. return box;
  55272. };
  55273. /**
  55274. * Creates a sphere mesh.
  55275. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  55276. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  55277. * 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`).
  55278. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  55279. * 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
  55280. * 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).
  55281. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55282. * 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).
  55283. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55284. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55285. */
  55286. MeshBuilder.CreateSphere = function (name, options, scene) {
  55287. var sphere = new BABYLON.Mesh(name, scene);
  55288. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55289. sphere._originalBuilderSideOrientation = options.sideOrientation;
  55290. var vertexData = BABYLON.VertexData.CreateSphere(options);
  55291. vertexData.applyToMesh(sphere, options.updatable);
  55292. return sphere;
  55293. };
  55294. /**
  55295. * Creates a plane polygonal mesh. By default, this is a disc.
  55296. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  55297. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  55298. * 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.
  55299. * 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
  55300. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55301. * 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).
  55302. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55303. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55304. */
  55305. MeshBuilder.CreateDisc = function (name, options, scene) {
  55306. if (scene === void 0) { scene = null; }
  55307. var disc = new BABYLON.Mesh(name, scene);
  55308. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55309. disc._originalBuilderSideOrientation = options.sideOrientation;
  55310. var vertexData = BABYLON.VertexData.CreateDisc(options);
  55311. vertexData.applyToMesh(disc, options.updatable);
  55312. return disc;
  55313. };
  55314. /**
  55315. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  55316. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  55317. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  55318. * 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`).
  55319. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  55320. * 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.
  55321. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55322. * 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).
  55323. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55324. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55325. */
  55326. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  55327. var sphere = new BABYLON.Mesh(name, scene);
  55328. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55329. sphere._originalBuilderSideOrientation = options.sideOrientation;
  55330. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  55331. vertexData.applyToMesh(sphere, options.updatable);
  55332. return sphere;
  55333. };
  55334. ;
  55335. /**
  55336. * Creates a ribbon mesh.
  55337. * 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.
  55338. *
  55339. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  55340. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  55341. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  55342. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  55343. * 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.
  55344. * 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.
  55345. * 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
  55346. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55347. * 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).
  55348. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55349. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55350. * 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.
  55351. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  55352. * 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
  55353. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  55354. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  55355. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55356. */
  55357. MeshBuilder.CreateRibbon = function (name, options, scene) {
  55358. if (scene === void 0) { scene = null; }
  55359. var pathArray = options.pathArray;
  55360. var closeArray = options.closeArray;
  55361. var closePath = options.closePath;
  55362. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55363. var instance = options.instance;
  55364. var updatable = options.updatable;
  55365. if (instance) {
  55366. // positionFunction : ribbon case
  55367. // only pathArray and sideOrientation parameters are taken into account for positions update
  55368. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  55369. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  55370. var positionFunction = function (positions) {
  55371. var minlg = pathArray[0].length;
  55372. var i = 0;
  55373. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  55374. for (var si = 1; si <= ns; si++) {
  55375. for (var p = 0; p < pathArray.length; p++) {
  55376. var path = pathArray[p];
  55377. var l = path.length;
  55378. minlg = (minlg < l) ? minlg : l;
  55379. var j = 0;
  55380. while (j < minlg) {
  55381. positions[i] = path[j].x;
  55382. positions[i + 1] = path[j].y;
  55383. positions[i + 2] = path[j].z;
  55384. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  55385. BABYLON.Tmp.Vector3[0].x = path[j].x;
  55386. }
  55387. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  55388. BABYLON.Tmp.Vector3[1].x = path[j].x;
  55389. }
  55390. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  55391. BABYLON.Tmp.Vector3[0].y = path[j].y;
  55392. }
  55393. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  55394. BABYLON.Tmp.Vector3[1].y = path[j].y;
  55395. }
  55396. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  55397. BABYLON.Tmp.Vector3[0].z = path[j].z;
  55398. }
  55399. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  55400. BABYLON.Tmp.Vector3[1].z = path[j].z;
  55401. }
  55402. j++;
  55403. i += 3;
  55404. }
  55405. if (instance._closePath) {
  55406. positions[i] = path[0].x;
  55407. positions[i + 1] = path[0].y;
  55408. positions[i + 2] = path[0].z;
  55409. i += 3;
  55410. }
  55411. }
  55412. }
  55413. };
  55414. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55415. positionFunction(positions);
  55416. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  55417. instance._boundingInfo.update(instance._worldMatrix);
  55418. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  55419. if (options.colors) {
  55420. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55421. for (var c = 0; c < options.colors.length; c++) {
  55422. colors[c * 4] = options.colors[c].r;
  55423. colors[c * 4 + 1] = options.colors[c].g;
  55424. colors[c * 4 + 2] = options.colors[c].b;
  55425. colors[c * 4 + 3] = options.colors[c].a;
  55426. }
  55427. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  55428. }
  55429. if (options.uvs) {
  55430. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55431. for (var i = 0; i < options.uvs.length; i++) {
  55432. uvs[i * 2] = options.uvs[i].x;
  55433. uvs[i * 2 + 1] = options.uvs[i].y;
  55434. }
  55435. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  55436. }
  55437. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  55438. var indices = instance.getIndices();
  55439. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55440. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  55441. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  55442. if (instance._closePath) {
  55443. var indexFirst = 0;
  55444. var indexLast = 0;
  55445. for (var p = 0; p < pathArray.length; p++) {
  55446. indexFirst = instance._idx[p] * 3;
  55447. if (p + 1 < pathArray.length) {
  55448. indexLast = (instance._idx[p + 1] - 1) * 3;
  55449. }
  55450. else {
  55451. indexLast = normals.length - 3;
  55452. }
  55453. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  55454. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  55455. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  55456. normals[indexLast] = normals[indexFirst];
  55457. normals[indexLast + 1] = normals[indexFirst + 1];
  55458. normals[indexLast + 2] = normals[indexFirst + 2];
  55459. }
  55460. }
  55461. if (!(instance.areNormalsFrozen)) {
  55462. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  55463. }
  55464. }
  55465. return instance;
  55466. }
  55467. else {
  55468. var ribbon = new BABYLON.Mesh(name, scene);
  55469. ribbon._originalBuilderSideOrientation = sideOrientation;
  55470. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  55471. if (closePath) {
  55472. ribbon._idx = vertexData._idx;
  55473. }
  55474. ribbon._closePath = closePath;
  55475. ribbon._closeArray = closeArray;
  55476. vertexData.applyToMesh(ribbon, updatable);
  55477. return ribbon;
  55478. }
  55479. };
  55480. /**
  55481. * Creates a cylinder or a cone mesh.
  55482. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  55483. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  55484. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  55485. * 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.
  55486. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  55487. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  55488. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  55489. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  55490. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  55491. * 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).
  55492. * 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
  55493. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  55494. * 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
  55495. * 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.
  55496. * If `enclose` is false, a ring surface is one element.
  55497. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  55498. * 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
  55499. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55500. * 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).
  55501. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55502. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55503. */
  55504. MeshBuilder.CreateCylinder = function (name, options, scene) {
  55505. var cylinder = new BABYLON.Mesh(name, scene);
  55506. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55507. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  55508. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  55509. vertexData.applyToMesh(cylinder, options.updatable);
  55510. return cylinder;
  55511. };
  55512. /**
  55513. * Creates a torus mesh.
  55514. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  55515. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  55516. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  55517. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  55518. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55519. * 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).
  55520. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55521. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55522. */
  55523. MeshBuilder.CreateTorus = function (name, options, scene) {
  55524. var torus = new BABYLON.Mesh(name, scene);
  55525. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55526. torus._originalBuilderSideOrientation = options.sideOrientation;
  55527. var vertexData = BABYLON.VertexData.CreateTorus(options);
  55528. vertexData.applyToMesh(torus, options.updatable);
  55529. return torus;
  55530. };
  55531. /**
  55532. * Creates a torus knot mesh.
  55533. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  55534. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  55535. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  55536. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  55537. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  55538. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55539. * 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).
  55540. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55541. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55542. */
  55543. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  55544. var torusKnot = new BABYLON.Mesh(name, scene);
  55545. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55546. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  55547. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  55548. vertexData.applyToMesh(torusKnot, options.updatable);
  55549. return torusKnot;
  55550. };
  55551. /**
  55552. * Creates a line system mesh.
  55553. * A line system is a pool of many lines gathered in a single mesh.
  55554. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  55555. * 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.
  55556. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  55557. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  55558. * 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
  55559. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  55560. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  55561. * 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
  55562. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  55563. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55564. */
  55565. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  55566. var instance = options.instance;
  55567. var lines = options.lines;
  55568. var colors = options.colors;
  55569. if (instance) {
  55570. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55571. var vertexColor;
  55572. var lineColors;
  55573. if (colors) {
  55574. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55575. }
  55576. var i = 0;
  55577. var c = 0;
  55578. for (var l = 0; l < lines.length; l++) {
  55579. var points = lines[l];
  55580. for (var p = 0; p < points.length; p++) {
  55581. positions[i] = points[p].x;
  55582. positions[i + 1] = points[p].y;
  55583. positions[i + 2] = points[p].z;
  55584. if (colors && vertexColor) {
  55585. lineColors = colors[l];
  55586. vertexColor[c] = lineColors[p].r;
  55587. vertexColor[c + 1] = lineColors[p].g;
  55588. vertexColor[c + 2] = lineColors[p].b;
  55589. vertexColor[c + 3] = lineColors[p].a;
  55590. c += 4;
  55591. }
  55592. i += 3;
  55593. }
  55594. }
  55595. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  55596. if (colors && vertexColor) {
  55597. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  55598. }
  55599. return instance;
  55600. }
  55601. // line system creation
  55602. var useVertexColor = (colors) ? true : false;
  55603. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  55604. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  55605. vertexData.applyToMesh(lineSystem, options.updatable);
  55606. return lineSystem;
  55607. };
  55608. /**
  55609. * Creates a line mesh.
  55610. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  55611. * 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.
  55612. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  55613. * The parameter `points` is an array successive Vector3.
  55614. * 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
  55615. * The optional parameter `colors` is an array of successive Color4, one per line point.
  55616. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  55617. * When updating an instance, remember that only point positions can change, not the number of points.
  55618. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55619. */
  55620. MeshBuilder.CreateLines = function (name, options, scene) {
  55621. if (scene === void 0) { scene = null; }
  55622. var colors = (options.colors) ? [options.colors] : null;
  55623. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  55624. return lines;
  55625. };
  55626. /**
  55627. * Creates a dashed line mesh.
  55628. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  55629. * 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.
  55630. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  55631. * The parameter `points` is an array successive Vector3.
  55632. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  55633. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  55634. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  55635. * 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
  55636. * When updating an instance, remember that only point positions can change, not the number of points.
  55637. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55638. */
  55639. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  55640. if (scene === void 0) { scene = null; }
  55641. var points = options.points;
  55642. var instance = options.instance;
  55643. var gapSize = options.gapSize || 1;
  55644. var dashSize = options.dashSize || 3;
  55645. if (instance) {
  55646. var positionFunction = function (positions) {
  55647. var curvect = BABYLON.Vector3.Zero();
  55648. var nbSeg = positions.length / 6;
  55649. var lg = 0;
  55650. var nb = 0;
  55651. var shft = 0;
  55652. var dashshft = 0;
  55653. var curshft = 0;
  55654. var p = 0;
  55655. var i = 0;
  55656. var j = 0;
  55657. for (i = 0; i < points.length - 1; i++) {
  55658. points[i + 1].subtractToRef(points[i], curvect);
  55659. lg += curvect.length();
  55660. }
  55661. shft = lg / nbSeg;
  55662. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  55663. for (i = 0; i < points.length - 1; i++) {
  55664. points[i + 1].subtractToRef(points[i], curvect);
  55665. nb = Math.floor(curvect.length() / shft);
  55666. curvect.normalize();
  55667. j = 0;
  55668. while (j < nb && p < positions.length) {
  55669. curshft = shft * j;
  55670. positions[p] = points[i].x + curshft * curvect.x;
  55671. positions[p + 1] = points[i].y + curshft * curvect.y;
  55672. positions[p + 2] = points[i].z + curshft * curvect.z;
  55673. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  55674. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  55675. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  55676. p += 6;
  55677. j++;
  55678. }
  55679. }
  55680. while (p < positions.length) {
  55681. positions[p] = points[i].x;
  55682. positions[p + 1] = points[i].y;
  55683. positions[p + 2] = points[i].z;
  55684. p += 3;
  55685. }
  55686. };
  55687. instance.updateMeshPositions(positionFunction, false);
  55688. return instance;
  55689. }
  55690. // dashed lines creation
  55691. var dashedLines = new BABYLON.LinesMesh(name, scene);
  55692. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  55693. vertexData.applyToMesh(dashedLines, options.updatable);
  55694. dashedLines.dashSize = dashSize;
  55695. dashedLines.gapSize = gapSize;
  55696. return dashedLines;
  55697. };
  55698. /**
  55699. * Creates an extruded shape mesh.
  55700. * 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.
  55701. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  55702. *
  55703. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  55704. * 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
  55705. * extruded along the Z axis.
  55706. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  55707. * 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.
  55708. * The parameter `scale` (float, default 1) is the value to scale the shape.
  55709. * 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
  55710. * 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
  55711. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  55712. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55713. * 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).
  55714. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55715. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55716. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55717. */
  55718. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  55719. if (scene === void 0) { scene = null; }
  55720. var path = options.path;
  55721. var shape = options.shape;
  55722. var scale = options.scale || 1;
  55723. var rotation = options.rotation || 0;
  55724. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  55725. var updatable = options.updatable;
  55726. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55727. var instance = options.instance || null;
  55728. var invertUV = options.invertUV || false;
  55729. 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);
  55730. };
  55731. /**
  55732. * Creates an custom extruded shape mesh.
  55733. * 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.
  55734. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  55735. *
  55736. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  55737. * 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
  55738. * extruded along the Z axis.
  55739. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  55740. * 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
  55741. * and the distance of this point from the begining of the path :
  55742. * ```javascript
  55743. * var rotationFunction = function(i, distance) {
  55744. * // do things
  55745. * return rotationValue; }
  55746. * ```
  55747. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  55748. * 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
  55749. * and the distance of this point from the begining of the path :
  55750. * ```javascript
  55751. * var scaleFunction = function(i, distance) {
  55752. * // do things
  55753. * return scaleValue;}
  55754. * ```
  55755. * It must returns a float value that will be the scale value applied to the shape on each path point.
  55756. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  55757. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  55758. * 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
  55759. * 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
  55760. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  55761. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55762. * 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).
  55763. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55764. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55765. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55766. */
  55767. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  55768. var path = options.path;
  55769. var shape = options.shape;
  55770. var scaleFunction = options.scaleFunction || (function () { return 1; });
  55771. var rotationFunction = options.rotationFunction || (function () { return 0; });
  55772. var ribbonCloseArray = options.ribbonCloseArray || false;
  55773. var ribbonClosePath = options.ribbonClosePath || false;
  55774. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  55775. var updatable = options.updatable;
  55776. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55777. var instance = options.instance;
  55778. var invertUV = options.invertUV || false;
  55779. 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);
  55780. };
  55781. /**
  55782. * Creates lathe mesh.
  55783. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  55784. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  55785. *
  55786. * 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
  55787. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  55788. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  55789. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  55790. * 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.
  55791. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  55792. * 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
  55793. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55794. * 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).
  55795. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55796. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55797. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55798. */
  55799. MeshBuilder.CreateLathe = function (name, options, scene) {
  55800. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  55801. var closed = (options.closed === undefined) ? true : options.closed;
  55802. var shape = options.shape;
  55803. var radius = options.radius || 1;
  55804. var tessellation = options.tessellation || 64;
  55805. var updatable = options.updatable;
  55806. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55807. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  55808. var pi2 = Math.PI * 2;
  55809. var paths = new Array();
  55810. var invertUV = options.invertUV || false;
  55811. var i = 0;
  55812. var p = 0;
  55813. var step = pi2 / tessellation * arc;
  55814. var rotated;
  55815. var path = new Array();
  55816. ;
  55817. for (i = 0; i <= tessellation; i++) {
  55818. var path = [];
  55819. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  55820. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  55821. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  55822. }
  55823. for (p = 0; p < shape.length; p++) {
  55824. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  55825. path.push(rotated);
  55826. }
  55827. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  55828. 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));
  55829. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  55830. }
  55831. paths.push(path);
  55832. }
  55833. // lathe ribbon
  55834. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  55835. return lathe;
  55836. };
  55837. /**
  55838. * Creates a plane mesh.
  55839. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  55840. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  55841. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  55842. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  55843. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55844. * 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).
  55845. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55846. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55847. */
  55848. MeshBuilder.CreatePlane = function (name, options, scene) {
  55849. var plane = new BABYLON.Mesh(name, scene);
  55850. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55851. plane._originalBuilderSideOrientation = options.sideOrientation;
  55852. var vertexData = BABYLON.VertexData.CreatePlane(options);
  55853. vertexData.applyToMesh(plane, options.updatable);
  55854. if (options.sourcePlane) {
  55855. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  55856. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  55857. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  55858. plane.rotate(vectorProduct, product);
  55859. }
  55860. return plane;
  55861. };
  55862. /**
  55863. * Creates a ground mesh.
  55864. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  55865. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  55866. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  55867. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55868. */
  55869. MeshBuilder.CreateGround = function (name, options, scene) {
  55870. var ground = new BABYLON.GroundMesh(name, scene);
  55871. ground._setReady(false);
  55872. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  55873. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  55874. ground._width = options.width || 1;
  55875. ground._height = options.height || 1;
  55876. ground._maxX = ground._width / 2;
  55877. ground._maxZ = ground._height / 2;
  55878. ground._minX = -ground._maxX;
  55879. ground._minZ = -ground._maxZ;
  55880. var vertexData = BABYLON.VertexData.CreateGround(options);
  55881. vertexData.applyToMesh(ground, options.updatable);
  55882. ground._setReady(true);
  55883. return ground;
  55884. };
  55885. /**
  55886. * Creates a tiled ground mesh.
  55887. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  55888. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  55889. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  55890. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  55891. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  55892. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  55893. * numbers of subdivisions on the ground width and height of each tile.
  55894. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55895. */
  55896. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  55897. var tiledGround = new BABYLON.Mesh(name, scene);
  55898. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  55899. vertexData.applyToMesh(tiledGround, options.updatable);
  55900. return tiledGround;
  55901. };
  55902. /**
  55903. * Creates a ground mesh from a height map.
  55904. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  55905. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  55906. * The parameter `url` sets the URL of the height map image resource.
  55907. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  55908. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  55909. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  55910. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  55911. * 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.
  55912. * 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).
  55913. * This function is passed the newly built mesh :
  55914. * ```javascript
  55915. * function(mesh) { // do things
  55916. * return; }
  55917. * ```
  55918. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55919. */
  55920. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  55921. var width = options.width || 10.0;
  55922. var height = options.height || 10.0;
  55923. var subdivisions = options.subdivisions || 1 | 0;
  55924. var minHeight = options.minHeight || 0.0;
  55925. var maxHeight = options.maxHeight || 1.0;
  55926. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  55927. var updatable = options.updatable;
  55928. var onReady = options.onReady;
  55929. var ground = new BABYLON.GroundMesh(name, scene);
  55930. ground._subdivisionsX = subdivisions;
  55931. ground._subdivisionsY = subdivisions;
  55932. ground._width = width;
  55933. ground._height = height;
  55934. ground._maxX = ground._width / 2.0;
  55935. ground._maxZ = ground._height / 2.0;
  55936. ground._minX = -ground._maxX;
  55937. ground._minZ = -ground._maxZ;
  55938. ground._setReady(false);
  55939. var onload = function (img) {
  55940. // Getting height map data
  55941. var canvas = document.createElement("canvas");
  55942. var context = canvas.getContext("2d");
  55943. if (!context) {
  55944. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  55945. }
  55946. if (scene.isDisposed) {
  55947. return;
  55948. }
  55949. var bufferWidth = img.width;
  55950. var bufferHeight = img.height;
  55951. canvas.width = bufferWidth;
  55952. canvas.height = bufferHeight;
  55953. context.drawImage(img, 0, 0);
  55954. // Create VertexData from map data
  55955. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  55956. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  55957. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  55958. width: width, height: height,
  55959. subdivisions: subdivisions,
  55960. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  55961. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  55962. });
  55963. vertexData.applyToMesh(ground, updatable);
  55964. ground._setReady(true);
  55965. //execute ready callback, if set
  55966. if (onReady) {
  55967. onReady(ground);
  55968. }
  55969. };
  55970. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  55971. return ground;
  55972. };
  55973. /**
  55974. * Creates a polygon mesh.
  55975. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  55976. * 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.
  55977. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55978. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55979. * 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).
  55980. * Remember you can only change the shape positions, not their number when updating a polygon.
  55981. */
  55982. MeshBuilder.CreatePolygon = function (name, options, scene) {
  55983. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55984. var shape = options.shape;
  55985. var holes = options.holes || [];
  55986. var depth = options.depth || 0;
  55987. var contours = [];
  55988. var hole = [];
  55989. for (var i = 0; i < shape.length; i++) {
  55990. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  55991. }
  55992. var epsilon = 0.00000001;
  55993. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  55994. contours.pop();
  55995. }
  55996. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  55997. for (var hNb = 0; hNb < holes.length; hNb++) {
  55998. hole = [];
  55999. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  56000. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  56001. }
  56002. polygonTriangulation.addHole(hole);
  56003. }
  56004. var polygon = polygonTriangulation.build(options.updatable, depth);
  56005. polygon._originalBuilderSideOrientation = options.sideOrientation;
  56006. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  56007. vertexData.applyToMesh(polygon, options.updatable);
  56008. return polygon;
  56009. };
  56010. ;
  56011. /**
  56012. * Creates an extruded polygon mesh, with depth in the Y direction.
  56013. * 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).
  56014. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  56015. */
  56016. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  56017. return MeshBuilder.CreatePolygon(name, options, scene);
  56018. };
  56019. ;
  56020. /**
  56021. * Creates a tube mesh.
  56022. * 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.
  56023. *
  56024. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  56025. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  56026. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  56027. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  56028. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  56029. * 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.
  56030. * It must return a radius value (positive float) :
  56031. * ```javascript
  56032. * var radiusFunction = function(i, distance) {
  56033. * // do things
  56034. * return radius; }
  56035. * ```
  56036. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  56037. * 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
  56038. * 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
  56039. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56040. * 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).
  56041. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56042. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56043. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56044. */
  56045. MeshBuilder.CreateTube = function (name, options, scene) {
  56046. var path = options.path;
  56047. var instance = options.instance;
  56048. var radius = 1.0;
  56049. if (instance) {
  56050. radius = instance.radius;
  56051. }
  56052. if (options.radius !== undefined) {
  56053. radius = options.radius;
  56054. }
  56055. ;
  56056. var tessellation = options.tessellation || 64 | 0;
  56057. var radiusFunction = options.radiusFunction || null;
  56058. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  56059. var invertUV = options.invertUV || false;
  56060. var updatable = options.updatable;
  56061. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56062. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  56063. // tube geometry
  56064. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  56065. var tangents = path3D.getTangents();
  56066. var normals = path3D.getNormals();
  56067. var distances = path3D.getDistances();
  56068. var pi2 = Math.PI * 2;
  56069. var step = pi2 / tessellation * arc;
  56070. var returnRadius = function () { return radius; };
  56071. var radiusFunctionFinal = radiusFunction || returnRadius;
  56072. var circlePath;
  56073. var rad;
  56074. var normal;
  56075. var rotated;
  56076. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  56077. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  56078. for (var i = 0; i < path.length; i++) {
  56079. rad = radiusFunctionFinal(i, distances[i]); // current radius
  56080. circlePath = Array(); // current circle array
  56081. normal = normals[i]; // current normal
  56082. for (var t = 0; t < tessellation; t++) {
  56083. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  56084. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  56085. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  56086. rotated.scaleInPlace(rad).addInPlace(path[i]);
  56087. circlePath[t] = rotated;
  56088. }
  56089. circlePaths[index] = circlePath;
  56090. index++;
  56091. }
  56092. // cap
  56093. var capPath = function (nbPoints, pathIndex) {
  56094. var pointCap = Array();
  56095. for (var i = 0; i < nbPoints; i++) {
  56096. pointCap.push(path[pathIndex]);
  56097. }
  56098. return pointCap;
  56099. };
  56100. switch (cap) {
  56101. case BABYLON.Mesh.NO_CAP:
  56102. break;
  56103. case BABYLON.Mesh.CAP_START:
  56104. circlePaths[0] = capPath(tessellation, 0);
  56105. circlePaths[1] = circlePaths[2].slice(0);
  56106. break;
  56107. case BABYLON.Mesh.CAP_END:
  56108. circlePaths[index] = circlePaths[index - 1].slice(0);
  56109. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  56110. break;
  56111. case BABYLON.Mesh.CAP_ALL:
  56112. circlePaths[0] = capPath(tessellation, 0);
  56113. circlePaths[1] = circlePaths[2].slice(0);
  56114. circlePaths[index] = circlePaths[index - 1].slice(0);
  56115. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  56116. break;
  56117. default:
  56118. break;
  56119. }
  56120. return circlePaths;
  56121. };
  56122. var path3D;
  56123. var pathArray;
  56124. if (instance) {
  56125. var arc = options.arc || instance.arc;
  56126. path3D = (instance.path3D).update(path);
  56127. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  56128. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  56129. instance.path3D = path3D;
  56130. instance.pathArray = pathArray;
  56131. instance.arc = arc;
  56132. instance.radius = radius;
  56133. return instance;
  56134. }
  56135. // tube creation
  56136. path3D = new BABYLON.Path3D(path);
  56137. var newPathArray = new Array();
  56138. cap = (cap < 0 || cap > 3) ? 0 : cap;
  56139. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  56140. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  56141. tube.pathArray = pathArray;
  56142. tube.path3D = path3D;
  56143. tube.tessellation = tessellation;
  56144. tube.cap = cap;
  56145. tube.arc = options.arc;
  56146. tube.radius = radius;
  56147. return tube;
  56148. };
  56149. /**
  56150. * Creates a polyhedron mesh.
  56151. *
  56152. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  56153. * 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
  56154. * to choose the wanted type.
  56155. * The parameter `size` (positive float, default 1) sets the polygon size.
  56156. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  56157. * 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`.
  56158. * 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
  56159. * 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)`).
  56160. * 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
  56161. * 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.
  56162. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56163. * 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).
  56164. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56165. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56166. */
  56167. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  56168. var polyhedron = new BABYLON.Mesh(name, scene);
  56169. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56170. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  56171. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  56172. vertexData.applyToMesh(polyhedron, options.updatable);
  56173. return polyhedron;
  56174. };
  56175. /**
  56176. * Creates a decal mesh.
  56177. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  56178. * 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.
  56179. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  56180. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  56181. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  56182. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  56183. */
  56184. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  56185. var indices = sourceMesh.getIndices();
  56186. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56187. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56188. var position = options.position || BABYLON.Vector3.Zero();
  56189. var normal = options.normal || BABYLON.Vector3.Up();
  56190. var size = options.size || BABYLON.Vector3.One();
  56191. var angle = options.angle || 0;
  56192. // Getting correct rotation
  56193. if (!normal) {
  56194. var target = new BABYLON.Vector3(0, 0, 1);
  56195. var camera = sourceMesh.getScene().activeCamera;
  56196. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  56197. normal = camera.globalPosition.subtract(cameraWorldTarget);
  56198. }
  56199. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  56200. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  56201. var pitch = Math.atan2(normal.y, len);
  56202. // Matrix
  56203. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  56204. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  56205. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  56206. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  56207. var vertexData = new BABYLON.VertexData();
  56208. vertexData.indices = [];
  56209. vertexData.positions = [];
  56210. vertexData.normals = [];
  56211. vertexData.uvs = [];
  56212. var currentVertexDataIndex = 0;
  56213. var extractDecalVector3 = function (indexId) {
  56214. var result = new BABYLON.PositionNormalVertex();
  56215. if (!indices || !positions || !normals) {
  56216. return result;
  56217. }
  56218. var vertexId = indices[indexId];
  56219. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  56220. // Send vector to decal local world
  56221. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  56222. // Get normal
  56223. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  56224. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  56225. return result;
  56226. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  56227. var clip = function (vertices, axis) {
  56228. if (vertices.length === 0) {
  56229. return vertices;
  56230. }
  56231. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  56232. var clipVertices = function (v0, v1) {
  56233. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  56234. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  56235. };
  56236. var result = new Array();
  56237. for (var index = 0; index < vertices.length; index += 3) {
  56238. var v1Out;
  56239. var v2Out;
  56240. var v3Out;
  56241. var total = 0;
  56242. var nV1 = null;
  56243. var nV2 = null;
  56244. var nV3 = null;
  56245. var nV4 = null;
  56246. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  56247. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  56248. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  56249. v1Out = d1 > 0;
  56250. v2Out = d2 > 0;
  56251. v3Out = d3 > 0;
  56252. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  56253. switch (total) {
  56254. case 0:
  56255. result.push(vertices[index]);
  56256. result.push(vertices[index + 1]);
  56257. result.push(vertices[index + 2]);
  56258. break;
  56259. case 1:
  56260. if (v1Out) {
  56261. nV1 = vertices[index + 1];
  56262. nV2 = vertices[index + 2];
  56263. nV3 = clipVertices(vertices[index], nV1);
  56264. nV4 = clipVertices(vertices[index], nV2);
  56265. }
  56266. if (v2Out) {
  56267. nV1 = vertices[index];
  56268. nV2 = vertices[index + 2];
  56269. nV3 = clipVertices(vertices[index + 1], nV1);
  56270. nV4 = clipVertices(vertices[index + 1], nV2);
  56271. result.push(nV3);
  56272. result.push(nV2.clone());
  56273. result.push(nV1.clone());
  56274. result.push(nV2.clone());
  56275. result.push(nV3.clone());
  56276. result.push(nV4);
  56277. break;
  56278. }
  56279. if (v3Out) {
  56280. nV1 = vertices[index];
  56281. nV2 = vertices[index + 1];
  56282. nV3 = clipVertices(vertices[index + 2], nV1);
  56283. nV4 = clipVertices(vertices[index + 2], nV2);
  56284. }
  56285. if (nV1 && nV2 && nV3 && nV4) {
  56286. result.push(nV1.clone());
  56287. result.push(nV2.clone());
  56288. result.push(nV3);
  56289. result.push(nV4);
  56290. result.push(nV3.clone());
  56291. result.push(nV2.clone());
  56292. }
  56293. break;
  56294. case 2:
  56295. if (!v1Out) {
  56296. nV1 = vertices[index].clone();
  56297. nV2 = clipVertices(nV1, vertices[index + 1]);
  56298. nV3 = clipVertices(nV1, vertices[index + 2]);
  56299. result.push(nV1);
  56300. result.push(nV2);
  56301. result.push(nV3);
  56302. }
  56303. if (!v2Out) {
  56304. nV1 = vertices[index + 1].clone();
  56305. nV2 = clipVertices(nV1, vertices[index + 2]);
  56306. nV3 = clipVertices(nV1, vertices[index]);
  56307. result.push(nV1);
  56308. result.push(nV2);
  56309. result.push(nV3);
  56310. }
  56311. if (!v3Out) {
  56312. nV1 = vertices[index + 2].clone();
  56313. nV2 = clipVertices(nV1, vertices[index]);
  56314. nV3 = clipVertices(nV1, vertices[index + 1]);
  56315. result.push(nV1);
  56316. result.push(nV2);
  56317. result.push(nV3);
  56318. }
  56319. break;
  56320. case 3:
  56321. break;
  56322. }
  56323. }
  56324. return result;
  56325. };
  56326. for (var index = 0; index < indices.length; index += 3) {
  56327. var faceVertices = new Array();
  56328. faceVertices.push(extractDecalVector3(index));
  56329. faceVertices.push(extractDecalVector3(index + 1));
  56330. faceVertices.push(extractDecalVector3(index + 2));
  56331. // Clip
  56332. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  56333. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  56334. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  56335. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  56336. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  56337. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  56338. if (faceVertices.length === 0) {
  56339. continue;
  56340. }
  56341. // Add UVs and get back to world
  56342. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  56343. var vertex = faceVertices[vIndex];
  56344. //TODO check for Int32Array | Uint32Array | Uint16Array
  56345. vertexData.indices.push(currentVertexDataIndex);
  56346. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  56347. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  56348. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  56349. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  56350. currentVertexDataIndex++;
  56351. }
  56352. }
  56353. // Return mesh
  56354. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  56355. vertexData.applyToMesh(decal);
  56356. decal.position = position.clone();
  56357. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  56358. return decal;
  56359. };
  56360. // Privates
  56361. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  56362. // extrusion geometry
  56363. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  56364. var tangents = path3D.getTangents();
  56365. var normals = path3D.getNormals();
  56366. var binormals = path3D.getBinormals();
  56367. var distances = path3D.getDistances();
  56368. var angle = 0;
  56369. var returnScale = function () { return scale !== null ? scale : 1; };
  56370. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  56371. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  56372. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  56373. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  56374. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  56375. for (var i = 0; i < curve.length; i++) {
  56376. var shapePath = new Array();
  56377. var angleStep = rotate(i, distances[i]);
  56378. var scaleRatio = scl(i, distances[i]);
  56379. for (var p = 0; p < shape.length; p++) {
  56380. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  56381. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  56382. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  56383. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  56384. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  56385. shapePath[p] = rotated;
  56386. }
  56387. shapePaths[index] = shapePath;
  56388. angle += angleStep;
  56389. index++;
  56390. }
  56391. // cap
  56392. var capPath = function (shapePath) {
  56393. var pointCap = Array();
  56394. var barycenter = BABYLON.Vector3.Zero();
  56395. var i;
  56396. for (i = 0; i < shapePath.length; i++) {
  56397. barycenter.addInPlace(shapePath[i]);
  56398. }
  56399. barycenter.scaleInPlace(1.0 / shapePath.length);
  56400. for (i = 0; i < shapePath.length; i++) {
  56401. pointCap.push(barycenter);
  56402. }
  56403. return pointCap;
  56404. };
  56405. switch (cap) {
  56406. case BABYLON.Mesh.NO_CAP:
  56407. break;
  56408. case BABYLON.Mesh.CAP_START:
  56409. shapePaths[0] = capPath(shapePaths[2]);
  56410. shapePaths[1] = shapePaths[2];
  56411. break;
  56412. case BABYLON.Mesh.CAP_END:
  56413. shapePaths[index] = shapePaths[index - 1];
  56414. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  56415. break;
  56416. case BABYLON.Mesh.CAP_ALL:
  56417. shapePaths[0] = capPath(shapePaths[2]);
  56418. shapePaths[1] = shapePaths[2];
  56419. shapePaths[index] = shapePaths[index - 1];
  56420. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  56421. break;
  56422. default:
  56423. break;
  56424. }
  56425. return shapePaths;
  56426. };
  56427. var path3D;
  56428. var pathArray;
  56429. if (instance) {
  56430. path3D = (instance.path3D).update(curve);
  56431. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  56432. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  56433. return instance;
  56434. }
  56435. // extruded shape creation
  56436. path3D = new BABYLON.Path3D(curve);
  56437. var newShapePaths = new Array();
  56438. cap = (cap < 0 || cap > 3) ? 0 : cap;
  56439. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  56440. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  56441. extrudedGeneric.pathArray = pathArray;
  56442. extrudedGeneric.path3D = path3D;
  56443. extrudedGeneric.cap = cap;
  56444. return extrudedGeneric;
  56445. };
  56446. return MeshBuilder;
  56447. }());
  56448. BABYLON.MeshBuilder = MeshBuilder;
  56449. })(BABYLON || (BABYLON = {}));
  56450. //# sourceMappingURL=babylon.meshBuilder.js.map
  56451. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  56452. var BABYLON;
  56453. (function (BABYLON) {
  56454. /**
  56455. * Draco compression (https://google.github.io/draco/)
  56456. */
  56457. var DracoCompression = /** @class */ (function () {
  56458. /**
  56459. * Constructor
  56460. * @param numWorkers The number of workers for async operations
  56461. */
  56462. function DracoCompression(numWorkers) {
  56463. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  56464. var workers = new Array(numWorkers);
  56465. for (var i = 0; i < workers.length; i++) {
  56466. var worker = new Worker(DracoCompression._WorkerBlobUrl);
  56467. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  56468. workers[i] = worker;
  56469. }
  56470. this._workerPool = new BABYLON.WorkerPool(workers);
  56471. }
  56472. /**
  56473. * Stop all async operations and release resources.
  56474. */
  56475. DracoCompression.prototype.dispose = function () {
  56476. this._workerPool.dispose();
  56477. delete this._workerPool;
  56478. };
  56479. /**
  56480. * Decode Draco compressed mesh data to vertex data.
  56481. * @param data The array buffer view for the Draco compression data
  56482. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  56483. * @returns A promise that resolves with the decoded vertex data
  56484. */
  56485. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  56486. var _this = this;
  56487. return new Promise(function (resolve, reject) {
  56488. _this._workerPool.push(function (worker, onComplete) {
  56489. var vertexData = new BABYLON.VertexData();
  56490. var onError = function (error) {
  56491. worker.removeEventListener("error", onError);
  56492. worker.removeEventListener("message", onMessage);
  56493. reject(error);
  56494. onComplete();
  56495. };
  56496. var onMessage = function (message) {
  56497. if (message.data === "done") {
  56498. worker.removeEventListener("error", onError);
  56499. worker.removeEventListener("message", onMessage);
  56500. resolve(vertexData);
  56501. onComplete();
  56502. }
  56503. else if (message.data.id === "indices") {
  56504. vertexData.indices = message.data.value;
  56505. }
  56506. else {
  56507. vertexData.set(message.data.value, message.data.id);
  56508. }
  56509. };
  56510. worker.addEventListener("error", onError);
  56511. worker.addEventListener("message", onMessage);
  56512. var dataCopy = new Uint8Array(data.byteLength);
  56513. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  56514. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  56515. });
  56516. });
  56517. };
  56518. /**
  56519. * The worker function that gets converted to a blob url to pass into a worker.
  56520. */
  56521. DracoCompression._Worker = function () {
  56522. // self is actually a DedicatedWorkerGlobalScope
  56523. var _self = self;
  56524. var decodeMesh = function (data, attributes) {
  56525. var dracoModule = new DracoDecoderModule();
  56526. var buffer = new dracoModule.DecoderBuffer();
  56527. buffer.Init(data, data.byteLength);
  56528. var decoder = new dracoModule.Decoder();
  56529. var geometry;
  56530. var status;
  56531. try {
  56532. var type = decoder.GetEncodedGeometryType(buffer);
  56533. switch (type) {
  56534. case dracoModule.TRIANGULAR_MESH:
  56535. geometry = new dracoModule.Mesh();
  56536. status = decoder.DecodeBufferToMesh(buffer, geometry);
  56537. break;
  56538. case dracoModule.POINT_CLOUD:
  56539. geometry = new dracoModule.PointCloud();
  56540. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  56541. break;
  56542. default:
  56543. throw new Error("Invalid geometry type " + type);
  56544. }
  56545. if (!status.ok() || !geometry.ptr) {
  56546. throw new Error(status.error_msg());
  56547. }
  56548. var numPoints = geometry.num_points();
  56549. if (type === dracoModule.TRIANGULAR_MESH) {
  56550. var numFaces = geometry.num_faces();
  56551. var faceIndices = new dracoModule.DracoInt32Array();
  56552. try {
  56553. var indices = new Uint32Array(numFaces * 3);
  56554. for (var i = 0; i < numFaces; i++) {
  56555. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  56556. var offset = i * 3;
  56557. indices[offset + 0] = faceIndices.GetValue(0);
  56558. indices[offset + 1] = faceIndices.GetValue(1);
  56559. indices[offset + 2] = faceIndices.GetValue(2);
  56560. }
  56561. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  56562. }
  56563. finally {
  56564. dracoModule.destroy(faceIndices);
  56565. }
  56566. }
  56567. for (var kind in attributes) {
  56568. var uniqueId = attributes[kind];
  56569. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  56570. var dracoData = new dracoModule.DracoFloat32Array();
  56571. try {
  56572. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  56573. var babylonData = new Float32Array(numPoints * attribute.num_components());
  56574. for (var i = 0; i < babylonData.length; i++) {
  56575. babylonData[i] = dracoData.GetValue(i);
  56576. }
  56577. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  56578. }
  56579. finally {
  56580. dracoModule.destroy(dracoData);
  56581. }
  56582. }
  56583. }
  56584. finally {
  56585. if (geometry) {
  56586. dracoModule.destroy(geometry);
  56587. }
  56588. dracoModule.destroy(decoder);
  56589. dracoModule.destroy(buffer);
  56590. }
  56591. _self.postMessage("done");
  56592. };
  56593. _self.onmessage = function (event) {
  56594. switch (event.data.id) {
  56595. case "initDecoder": {
  56596. importScripts(event.data.url);
  56597. break;
  56598. }
  56599. case "decodeMesh": {
  56600. decodeMesh(event.data.data, event.data.attributes);
  56601. break;
  56602. }
  56603. }
  56604. };
  56605. };
  56606. DracoCompression._GetDefaultDecoderUrl = function () {
  56607. for (var i = 0; i < document.scripts.length; i++) {
  56608. if (document.scripts[i].type === "text/x-draco-decoder") {
  56609. return document.scripts[i].src;
  56610. }
  56611. }
  56612. return null;
  56613. };
  56614. /**
  56615. * Gets the url to the draco decoder if available.
  56616. */
  56617. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  56618. DracoCompression._WorkerBlobUrl = URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  56619. return DracoCompression;
  56620. }());
  56621. BABYLON.DracoCompression = DracoCompression;
  56622. })(BABYLON || (BABYLON = {}));
  56623. //# sourceMappingURL=babylon.dracoCompression.js.map
  56624. var BABYLON;
  56625. (function (BABYLON) {
  56626. var AudioEngine = /** @class */ (function () {
  56627. function AudioEngine() {
  56628. this._audioContext = null;
  56629. this._audioContextInitialized = false;
  56630. this.canUseWebAudio = false;
  56631. this.WarnedWebAudioUnsupported = false;
  56632. this.unlocked = false;
  56633. this.isMP3supported = false;
  56634. this.isOGGsupported = false;
  56635. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  56636. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  56637. this.canUseWebAudio = true;
  56638. }
  56639. var audioElem = document.createElement('audio');
  56640. try {
  56641. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  56642. this.isMP3supported = true;
  56643. }
  56644. }
  56645. catch (e) {
  56646. // protect error during capability check.
  56647. }
  56648. try {
  56649. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  56650. this.isOGGsupported = true;
  56651. }
  56652. }
  56653. catch (e) {
  56654. // protect error during capability check.
  56655. }
  56656. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  56657. this._unlockiOSaudio();
  56658. }
  56659. else {
  56660. this.unlocked = true;
  56661. }
  56662. }
  56663. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  56664. get: function () {
  56665. if (!this._audioContextInitialized) {
  56666. this._initializeAudioContext();
  56667. }
  56668. return this._audioContext;
  56669. },
  56670. enumerable: true,
  56671. configurable: true
  56672. });
  56673. AudioEngine.prototype._unlockiOSaudio = function () {
  56674. var _this = this;
  56675. var unlockaudio = function () {
  56676. if (!_this.audioContext) {
  56677. return;
  56678. }
  56679. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  56680. var source = _this.audioContext.createBufferSource();
  56681. source.buffer = buffer;
  56682. source.connect(_this.audioContext.destination);
  56683. source.start(0);
  56684. setTimeout(function () {
  56685. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  56686. _this.unlocked = true;
  56687. window.removeEventListener('touchend', unlockaudio, false);
  56688. if (_this.onAudioUnlocked) {
  56689. _this.onAudioUnlocked();
  56690. }
  56691. }
  56692. }, 0);
  56693. };
  56694. window.addEventListener('touchend', unlockaudio, false);
  56695. };
  56696. AudioEngine.prototype._initializeAudioContext = function () {
  56697. try {
  56698. if (this.canUseWebAudio) {
  56699. this._audioContext = new AudioContext();
  56700. // create a global volume gain node
  56701. this.masterGain = this._audioContext.createGain();
  56702. this.masterGain.gain.value = 1;
  56703. this.masterGain.connect(this._audioContext.destination);
  56704. this._audioContextInitialized = true;
  56705. }
  56706. }
  56707. catch (e) {
  56708. this.canUseWebAudio = false;
  56709. BABYLON.Tools.Error("Web Audio: " + e.message);
  56710. }
  56711. };
  56712. AudioEngine.prototype.dispose = function () {
  56713. if (this.canUseWebAudio && this._audioContextInitialized) {
  56714. if (this._connectedAnalyser && this._audioContext) {
  56715. this._connectedAnalyser.stopDebugCanvas();
  56716. this._connectedAnalyser.dispose();
  56717. this.masterGain.disconnect();
  56718. this.masterGain.connect(this._audioContext.destination);
  56719. this._connectedAnalyser = null;
  56720. }
  56721. this.masterGain.gain.value = 1;
  56722. }
  56723. this.WarnedWebAudioUnsupported = false;
  56724. };
  56725. AudioEngine.prototype.getGlobalVolume = function () {
  56726. if (this.canUseWebAudio && this._audioContextInitialized) {
  56727. return this.masterGain.gain.value;
  56728. }
  56729. else {
  56730. return -1;
  56731. }
  56732. };
  56733. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  56734. if (this.canUseWebAudio && this._audioContextInitialized) {
  56735. this.masterGain.gain.value = newVolume;
  56736. }
  56737. };
  56738. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  56739. if (this._connectedAnalyser) {
  56740. this._connectedAnalyser.stopDebugCanvas();
  56741. }
  56742. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  56743. this._connectedAnalyser = analyser;
  56744. this.masterGain.disconnect();
  56745. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  56746. }
  56747. };
  56748. return AudioEngine;
  56749. }());
  56750. BABYLON.AudioEngine = AudioEngine;
  56751. })(BABYLON || (BABYLON = {}));
  56752. //# sourceMappingURL=babylon.audioEngine.js.map
  56753. var BABYLON;
  56754. (function (BABYLON) {
  56755. var Sound = /** @class */ (function () {
  56756. /**
  56757. * Create a sound and attach it to a scene
  56758. * @param name Name of your sound
  56759. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  56760. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  56761. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  56762. */
  56763. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  56764. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  56765. var _this = this;
  56766. this.autoplay = false;
  56767. this.loop = false;
  56768. this.useCustomAttenuation = false;
  56769. this.spatialSound = false;
  56770. this.refDistance = 1;
  56771. this.rolloffFactor = 1;
  56772. this.maxDistance = 100;
  56773. this.distanceModel = "linear";
  56774. this._panningModel = "equalpower";
  56775. this._playbackRate = 1;
  56776. this._streaming = false;
  56777. this._startTime = 0;
  56778. this._startOffset = 0;
  56779. this._position = BABYLON.Vector3.Zero();
  56780. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  56781. this._volume = 1;
  56782. this._isReadyToPlay = false;
  56783. this.isPlaying = false;
  56784. this.isPaused = false;
  56785. this._isDirectional = false;
  56786. // Used if you'd like to create a directional sound.
  56787. // If not set, the sound will be omnidirectional
  56788. this._coneInnerAngle = 360;
  56789. this._coneOuterAngle = 360;
  56790. this._coneOuterGain = 0;
  56791. this._isOutputConnected = false;
  56792. this._urlType = "Unknown";
  56793. this.name = name;
  56794. this._scene = scene;
  56795. this._readyToPlayCallback = readyToPlayCallback;
  56796. // Default custom attenuation function is a linear attenuation
  56797. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  56798. if (currentDistance < maxDistance) {
  56799. return currentVolume * (1 - currentDistance / maxDistance);
  56800. }
  56801. else {
  56802. return 0;
  56803. }
  56804. };
  56805. if (options) {
  56806. this.autoplay = options.autoplay || false;
  56807. this.loop = options.loop || false;
  56808. // if volume === 0, we need another way to check this option
  56809. if (options.volume !== undefined) {
  56810. this._volume = options.volume;
  56811. }
  56812. this.spatialSound = options.spatialSound || false;
  56813. this.maxDistance = options.maxDistance || 100;
  56814. this.useCustomAttenuation = options.useCustomAttenuation || false;
  56815. this.rolloffFactor = options.rolloffFactor || 1;
  56816. this.refDistance = options.refDistance || 1;
  56817. this.distanceModel = options.distanceModel || "linear";
  56818. this._playbackRate = options.playbackRate || 1;
  56819. this._streaming = options.streaming || false;
  56820. }
  56821. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56822. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  56823. this._soundGain.gain.value = this._volume;
  56824. this._inputAudioNode = this._soundGain;
  56825. this._ouputAudioNode = this._soundGain;
  56826. if (this.spatialSound) {
  56827. this._createSpatialParameters();
  56828. }
  56829. this._scene.mainSoundTrack.AddSound(this);
  56830. var validParameter = true;
  56831. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  56832. if (urlOrArrayBuffer) {
  56833. if (typeof (urlOrArrayBuffer) === "string")
  56834. this._urlType = "String";
  56835. if (Array.isArray(urlOrArrayBuffer))
  56836. this._urlType = "Array";
  56837. if (urlOrArrayBuffer instanceof ArrayBuffer)
  56838. this._urlType = "ArrayBuffer";
  56839. var urls = [];
  56840. var codecSupportedFound = false;
  56841. switch (this._urlType) {
  56842. case "ArrayBuffer":
  56843. if (urlOrArrayBuffer.byteLength > 0) {
  56844. codecSupportedFound = true;
  56845. this._soundLoaded(urlOrArrayBuffer);
  56846. }
  56847. break;
  56848. case "String":
  56849. urls.push(urlOrArrayBuffer);
  56850. case "Array":
  56851. if (urls.length === 0)
  56852. urls = urlOrArrayBuffer;
  56853. // If we found a supported format, we load it immediately and stop the loop
  56854. for (var i = 0; i < urls.length; i++) {
  56855. var url = urls[i];
  56856. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  56857. codecSupportedFound = true;
  56858. }
  56859. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  56860. codecSupportedFound = true;
  56861. }
  56862. if (url.indexOf(".wav", url.length - 4) !== -1) {
  56863. codecSupportedFound = true;
  56864. }
  56865. if (url.indexOf("blob:") !== -1) {
  56866. codecSupportedFound = true;
  56867. }
  56868. if (codecSupportedFound) {
  56869. // Loading sound using XHR2
  56870. if (!this._streaming) {
  56871. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  56872. }
  56873. else {
  56874. this._htmlAudioElement = new Audio(url);
  56875. this._htmlAudioElement.controls = false;
  56876. this._htmlAudioElement.loop = this.loop;
  56877. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  56878. this._htmlAudioElement.preload = "auto";
  56879. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  56880. _this._isReadyToPlay = true;
  56881. if (_this.autoplay) {
  56882. _this.play();
  56883. }
  56884. if (_this._readyToPlayCallback) {
  56885. _this._readyToPlayCallback();
  56886. }
  56887. });
  56888. document.body.appendChild(this._htmlAudioElement);
  56889. }
  56890. break;
  56891. }
  56892. }
  56893. break;
  56894. default:
  56895. validParameter = false;
  56896. break;
  56897. }
  56898. if (!validParameter) {
  56899. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  56900. }
  56901. else {
  56902. if (!codecSupportedFound) {
  56903. this._isReadyToPlay = true;
  56904. // Simulating a ready to play event to avoid breaking code path
  56905. if (this._readyToPlayCallback) {
  56906. window.setTimeout(function () {
  56907. if (_this._readyToPlayCallback) {
  56908. _this._readyToPlayCallback();
  56909. }
  56910. }, 1000);
  56911. }
  56912. }
  56913. }
  56914. }
  56915. }
  56916. else {
  56917. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  56918. this._scene.mainSoundTrack.AddSound(this);
  56919. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  56920. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  56921. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  56922. }
  56923. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  56924. if (this._readyToPlayCallback) {
  56925. window.setTimeout(function () {
  56926. if (_this._readyToPlayCallback) {
  56927. _this._readyToPlayCallback();
  56928. }
  56929. }, 1000);
  56930. }
  56931. }
  56932. }
  56933. Sound.prototype.dispose = function () {
  56934. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  56935. if (this.isPlaying) {
  56936. this.stop();
  56937. }
  56938. this._isReadyToPlay = false;
  56939. if (this.soundTrackId === -1) {
  56940. this._scene.mainSoundTrack.RemoveSound(this);
  56941. }
  56942. else {
  56943. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  56944. }
  56945. if (this._soundGain) {
  56946. this._soundGain.disconnect();
  56947. this._soundGain = null;
  56948. }
  56949. if (this._soundPanner) {
  56950. this._soundPanner.disconnect();
  56951. this._soundPanner = null;
  56952. }
  56953. if (this._soundSource) {
  56954. this._soundSource.disconnect();
  56955. this._soundSource = null;
  56956. }
  56957. this._audioBuffer = null;
  56958. if (this._htmlAudioElement) {
  56959. this._htmlAudioElement.pause();
  56960. this._htmlAudioElement.src = "";
  56961. document.body.removeChild(this._htmlAudioElement);
  56962. }
  56963. if (this._connectedMesh && this._registerFunc) {
  56964. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56965. this._connectedMesh = null;
  56966. }
  56967. }
  56968. };
  56969. Sound.prototype.isReady = function () {
  56970. return this._isReadyToPlay;
  56971. };
  56972. Sound.prototype._soundLoaded = function (audioData) {
  56973. var _this = this;
  56974. if (!BABYLON.Engine.audioEngine.audioContext) {
  56975. return;
  56976. }
  56977. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  56978. _this._audioBuffer = buffer;
  56979. _this._isReadyToPlay = true;
  56980. if (_this.autoplay) {
  56981. _this.play();
  56982. }
  56983. if (_this._readyToPlayCallback) {
  56984. _this._readyToPlayCallback();
  56985. }
  56986. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  56987. };
  56988. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  56989. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56990. this._audioBuffer = audioBuffer;
  56991. this._isReadyToPlay = true;
  56992. }
  56993. };
  56994. Sound.prototype.updateOptions = function (options) {
  56995. if (options) {
  56996. this.loop = options.loop || this.loop;
  56997. this.maxDistance = options.maxDistance || this.maxDistance;
  56998. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  56999. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  57000. this.refDistance = options.refDistance || this.refDistance;
  57001. this.distanceModel = options.distanceModel || this.distanceModel;
  57002. this._playbackRate = options.playbackRate || this._playbackRate;
  57003. this._updateSpatialParameters();
  57004. if (this.isPlaying) {
  57005. if (this._streaming) {
  57006. this._htmlAudioElement.playbackRate = this._playbackRate;
  57007. }
  57008. else {
  57009. if (this._soundSource) {
  57010. this._soundSource.playbackRate.value = this._playbackRate;
  57011. }
  57012. }
  57013. }
  57014. }
  57015. };
  57016. Sound.prototype._createSpatialParameters = function () {
  57017. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57018. if (this._scene.headphone) {
  57019. this._panningModel = "HRTF";
  57020. }
  57021. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  57022. this._updateSpatialParameters();
  57023. this._soundPanner.connect(this._ouputAudioNode);
  57024. this._inputAudioNode = this._soundPanner;
  57025. }
  57026. };
  57027. Sound.prototype._updateSpatialParameters = function () {
  57028. if (this.spatialSound && this._soundPanner) {
  57029. if (this.useCustomAttenuation) {
  57030. // Tricks to disable in a way embedded Web Audio attenuation
  57031. this._soundPanner.distanceModel = "linear";
  57032. this._soundPanner.maxDistance = Number.MAX_VALUE;
  57033. this._soundPanner.refDistance = 1;
  57034. this._soundPanner.rolloffFactor = 1;
  57035. this._soundPanner.panningModel = this._panningModel;
  57036. }
  57037. else {
  57038. this._soundPanner.distanceModel = this.distanceModel;
  57039. this._soundPanner.maxDistance = this.maxDistance;
  57040. this._soundPanner.refDistance = this.refDistance;
  57041. this._soundPanner.rolloffFactor = this.rolloffFactor;
  57042. this._soundPanner.panningModel = this._panningModel;
  57043. }
  57044. }
  57045. };
  57046. Sound.prototype.switchPanningModelToHRTF = function () {
  57047. this._panningModel = "HRTF";
  57048. this._switchPanningModel();
  57049. };
  57050. Sound.prototype.switchPanningModelToEqualPower = function () {
  57051. this._panningModel = "equalpower";
  57052. this._switchPanningModel();
  57053. };
  57054. Sound.prototype._switchPanningModel = function () {
  57055. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  57056. this._soundPanner.panningModel = this._panningModel;
  57057. }
  57058. };
  57059. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  57060. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57061. if (this._isOutputConnected) {
  57062. this._ouputAudioNode.disconnect();
  57063. }
  57064. this._ouputAudioNode.connect(soundTrackAudioNode);
  57065. this._isOutputConnected = true;
  57066. }
  57067. };
  57068. /**
  57069. * Transform this sound into a directional source
  57070. * @param coneInnerAngle Size of the inner cone in degree
  57071. * @param coneOuterAngle Size of the outer cone in degree
  57072. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  57073. */
  57074. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  57075. if (coneOuterAngle < coneInnerAngle) {
  57076. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  57077. return;
  57078. }
  57079. this._coneInnerAngle = coneInnerAngle;
  57080. this._coneOuterAngle = coneOuterAngle;
  57081. this._coneOuterGain = coneOuterGain;
  57082. this._isDirectional = true;
  57083. if (this.isPlaying && this.loop) {
  57084. this.stop();
  57085. this.play();
  57086. }
  57087. };
  57088. Sound.prototype.setPosition = function (newPosition) {
  57089. this._position = newPosition;
  57090. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  57091. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  57092. }
  57093. };
  57094. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  57095. this._localDirection = newLocalDirection;
  57096. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  57097. this._updateDirection();
  57098. }
  57099. };
  57100. Sound.prototype._updateDirection = function () {
  57101. if (!this._connectedMesh || !this._soundPanner) {
  57102. return;
  57103. }
  57104. var mat = this._connectedMesh.getWorldMatrix();
  57105. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  57106. direction.normalize();
  57107. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  57108. };
  57109. Sound.prototype.updateDistanceFromListener = function () {
  57110. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  57111. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  57112. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  57113. }
  57114. };
  57115. Sound.prototype.setAttenuationFunction = function (callback) {
  57116. this._customAttenuationFunction = callback;
  57117. };
  57118. /**
  57119. * Play the sound
  57120. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  57121. * @param offset (optional) Start the sound setting it at a specific time
  57122. */
  57123. Sound.prototype.play = function (time, offset) {
  57124. var _this = this;
  57125. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  57126. try {
  57127. if (this._startOffset < 0) {
  57128. time = -this._startOffset;
  57129. this._startOffset = 0;
  57130. }
  57131. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  57132. if (!this._soundSource || !this._streamingSource) {
  57133. if (this.spatialSound && this._soundPanner) {
  57134. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  57135. if (this._isDirectional) {
  57136. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  57137. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  57138. this._soundPanner.coneOuterGain = this._coneOuterGain;
  57139. if (this._connectedMesh) {
  57140. this._updateDirection();
  57141. }
  57142. else {
  57143. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  57144. }
  57145. }
  57146. }
  57147. }
  57148. if (this._streaming) {
  57149. if (!this._streamingSource) {
  57150. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  57151. this._htmlAudioElement.onended = function () { _this._onended(); };
  57152. this._htmlAudioElement.playbackRate = this._playbackRate;
  57153. }
  57154. this._streamingSource.disconnect();
  57155. this._streamingSource.connect(this._inputAudioNode);
  57156. this._htmlAudioElement.play();
  57157. }
  57158. else {
  57159. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  57160. this._soundSource.buffer = this._audioBuffer;
  57161. this._soundSource.connect(this._inputAudioNode);
  57162. this._soundSource.loop = this.loop;
  57163. this._soundSource.playbackRate.value = this._playbackRate;
  57164. this._soundSource.onended = function () { _this._onended(); };
  57165. if (this._soundSource.buffer) {
  57166. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  57167. }
  57168. }
  57169. this._startTime = startTime;
  57170. this.isPlaying = true;
  57171. this.isPaused = false;
  57172. }
  57173. catch (ex) {
  57174. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  57175. }
  57176. }
  57177. };
  57178. Sound.prototype._onended = function () {
  57179. this.isPlaying = false;
  57180. if (this.onended) {
  57181. this.onended();
  57182. }
  57183. };
  57184. /**
  57185. * Stop the sound
  57186. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  57187. */
  57188. Sound.prototype.stop = function (time) {
  57189. if (this.isPlaying) {
  57190. if (this._streaming) {
  57191. this._htmlAudioElement.pause();
  57192. // Test needed for Firefox or it will generate an Invalid State Error
  57193. if (this._htmlAudioElement.currentTime > 0) {
  57194. this._htmlAudioElement.currentTime = 0;
  57195. }
  57196. }
  57197. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  57198. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  57199. this._soundSource.stop(stopTime);
  57200. this._soundSource.onended = function () { };
  57201. if (!this.isPaused) {
  57202. this._startOffset = 0;
  57203. }
  57204. }
  57205. this.isPlaying = false;
  57206. }
  57207. };
  57208. Sound.prototype.pause = function () {
  57209. if (this.isPlaying) {
  57210. this.isPaused = true;
  57211. if (this._streaming) {
  57212. this._htmlAudioElement.pause();
  57213. }
  57214. else if (BABYLON.Engine.audioEngine.audioContext) {
  57215. this.stop(0);
  57216. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  57217. }
  57218. }
  57219. };
  57220. Sound.prototype.setVolume = function (newVolume, time) {
  57221. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  57222. if (time && BABYLON.Engine.audioEngine.audioContext) {
  57223. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  57224. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  57225. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  57226. }
  57227. else {
  57228. this._soundGain.gain.value = newVolume;
  57229. }
  57230. }
  57231. this._volume = newVolume;
  57232. };
  57233. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  57234. this._playbackRate = newPlaybackRate;
  57235. if (this.isPlaying) {
  57236. if (this._streaming) {
  57237. this._htmlAudioElement.playbackRate = this._playbackRate;
  57238. }
  57239. else if (this._soundSource) {
  57240. this._soundSource.playbackRate.value = this._playbackRate;
  57241. }
  57242. }
  57243. };
  57244. Sound.prototype.getVolume = function () {
  57245. return this._volume;
  57246. };
  57247. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  57248. var _this = this;
  57249. if (this._connectedMesh && this._registerFunc) {
  57250. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57251. this._registerFunc = null;
  57252. }
  57253. this._connectedMesh = meshToConnectTo;
  57254. if (!this.spatialSound) {
  57255. this.spatialSound = true;
  57256. this._createSpatialParameters();
  57257. if (this.isPlaying && this.loop) {
  57258. this.stop();
  57259. this.play();
  57260. }
  57261. }
  57262. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  57263. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  57264. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  57265. };
  57266. Sound.prototype.detachFromMesh = function () {
  57267. if (this._connectedMesh && this._registerFunc) {
  57268. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57269. this._registerFunc = null;
  57270. this._connectedMesh = null;
  57271. }
  57272. };
  57273. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  57274. if (!node.getBoundingInfo) {
  57275. return;
  57276. }
  57277. var mesh = node;
  57278. var boundingInfo = mesh.getBoundingInfo();
  57279. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  57280. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  57281. this._updateDirection();
  57282. }
  57283. };
  57284. Sound.prototype.clone = function () {
  57285. var _this = this;
  57286. if (!this._streaming) {
  57287. var setBufferAndRun = function () {
  57288. if (_this._isReadyToPlay) {
  57289. clonedSound._audioBuffer = _this.getAudioBuffer();
  57290. clonedSound._isReadyToPlay = true;
  57291. if (clonedSound.autoplay) {
  57292. clonedSound.play();
  57293. }
  57294. }
  57295. else {
  57296. window.setTimeout(setBufferAndRun, 300);
  57297. }
  57298. };
  57299. var currentOptions = {
  57300. autoplay: this.autoplay, loop: this.loop,
  57301. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  57302. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  57303. refDistance: this.refDistance, distanceModel: this.distanceModel
  57304. };
  57305. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  57306. if (this.useCustomAttenuation) {
  57307. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  57308. }
  57309. clonedSound.setPosition(this._position);
  57310. clonedSound.setPlaybackRate(this._playbackRate);
  57311. setBufferAndRun();
  57312. return clonedSound;
  57313. }
  57314. else {
  57315. return null;
  57316. }
  57317. };
  57318. Sound.prototype.getAudioBuffer = function () {
  57319. return this._audioBuffer;
  57320. };
  57321. Sound.prototype.serialize = function () {
  57322. var serializationObject = {
  57323. name: this.name,
  57324. url: this.name,
  57325. autoplay: this.autoplay,
  57326. loop: this.loop,
  57327. volume: this._volume,
  57328. spatialSound: this.spatialSound,
  57329. maxDistance: this.maxDistance,
  57330. rolloffFactor: this.rolloffFactor,
  57331. refDistance: this.refDistance,
  57332. distanceModel: this.distanceModel,
  57333. playbackRate: this._playbackRate,
  57334. panningModel: this._panningModel,
  57335. soundTrackId: this.soundTrackId
  57336. };
  57337. if (this.spatialSound) {
  57338. if (this._connectedMesh)
  57339. serializationObject.connectedMeshId = this._connectedMesh.id;
  57340. serializationObject.position = this._position.asArray();
  57341. serializationObject.refDistance = this.refDistance;
  57342. serializationObject.distanceModel = this.distanceModel;
  57343. serializationObject.isDirectional = this._isDirectional;
  57344. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  57345. serializationObject.coneInnerAngle = this._coneInnerAngle;
  57346. serializationObject.coneOuterAngle = this._coneOuterAngle;
  57347. serializationObject.coneOuterGain = this._coneOuterGain;
  57348. }
  57349. return serializationObject;
  57350. };
  57351. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  57352. var soundName = parsedSound.name;
  57353. var soundUrl;
  57354. if (parsedSound.url) {
  57355. soundUrl = rootUrl + parsedSound.url;
  57356. }
  57357. else {
  57358. soundUrl = rootUrl + soundName;
  57359. }
  57360. var options = {
  57361. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  57362. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  57363. rolloffFactor: parsedSound.rolloffFactor,
  57364. refDistance: parsedSound.refDistance,
  57365. distanceModel: parsedSound.distanceModel,
  57366. playbackRate: parsedSound.playbackRate
  57367. };
  57368. var newSound;
  57369. if (!sourceSound) {
  57370. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  57371. scene._addPendingData(newSound);
  57372. }
  57373. else {
  57374. var setBufferAndRun = function () {
  57375. if (sourceSound._isReadyToPlay) {
  57376. newSound._audioBuffer = sourceSound.getAudioBuffer();
  57377. newSound._isReadyToPlay = true;
  57378. if (newSound.autoplay) {
  57379. newSound.play();
  57380. }
  57381. }
  57382. else {
  57383. window.setTimeout(setBufferAndRun, 300);
  57384. }
  57385. };
  57386. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  57387. setBufferAndRun();
  57388. }
  57389. if (parsedSound.position) {
  57390. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  57391. newSound.setPosition(soundPosition);
  57392. }
  57393. if (parsedSound.isDirectional) {
  57394. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  57395. if (parsedSound.localDirectionToMesh) {
  57396. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  57397. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  57398. }
  57399. }
  57400. if (parsedSound.connectedMeshId) {
  57401. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  57402. if (connectedMesh) {
  57403. newSound.attachToMesh(connectedMesh);
  57404. }
  57405. }
  57406. return newSound;
  57407. };
  57408. return Sound;
  57409. }());
  57410. BABYLON.Sound = Sound;
  57411. })(BABYLON || (BABYLON = {}));
  57412. //# sourceMappingURL=babylon.sound.js.map
  57413. var BABYLON;
  57414. (function (BABYLON) {
  57415. var SoundTrack = /** @class */ (function () {
  57416. function SoundTrack(scene, options) {
  57417. this.id = -1;
  57418. this._isMainTrack = false;
  57419. this._isInitialized = false;
  57420. this._scene = scene;
  57421. this.soundCollection = new Array();
  57422. this._options = options;
  57423. if (!this._isMainTrack) {
  57424. this._scene.soundTracks.push(this);
  57425. this.id = this._scene.soundTracks.length - 1;
  57426. }
  57427. }
  57428. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  57429. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57430. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  57431. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  57432. if (this._options) {
  57433. if (this._options.volume) {
  57434. this._outputAudioNode.gain.value = this._options.volume;
  57435. }
  57436. if (this._options.mainTrack) {
  57437. this._isMainTrack = this._options.mainTrack;
  57438. }
  57439. }
  57440. this._isInitialized = true;
  57441. }
  57442. };
  57443. SoundTrack.prototype.dispose = function () {
  57444. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  57445. if (this._connectedAnalyser) {
  57446. this._connectedAnalyser.stopDebugCanvas();
  57447. }
  57448. while (this.soundCollection.length) {
  57449. this.soundCollection[0].dispose();
  57450. }
  57451. if (this._outputAudioNode) {
  57452. this._outputAudioNode.disconnect();
  57453. }
  57454. this._outputAudioNode = null;
  57455. }
  57456. };
  57457. SoundTrack.prototype.AddSound = function (sound) {
  57458. if (!this._isInitialized) {
  57459. this._initializeSoundTrackAudioGraph();
  57460. }
  57461. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57462. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  57463. }
  57464. if (sound.soundTrackId) {
  57465. if (sound.soundTrackId === -1) {
  57466. this._scene.mainSoundTrack.RemoveSound(sound);
  57467. }
  57468. else {
  57469. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  57470. }
  57471. }
  57472. this.soundCollection.push(sound);
  57473. sound.soundTrackId = this.id;
  57474. };
  57475. SoundTrack.prototype.RemoveSound = function (sound) {
  57476. var index = this.soundCollection.indexOf(sound);
  57477. if (index !== -1) {
  57478. this.soundCollection.splice(index, 1);
  57479. }
  57480. };
  57481. SoundTrack.prototype.setVolume = function (newVolume) {
  57482. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57483. this._outputAudioNode.gain.value = newVolume;
  57484. }
  57485. };
  57486. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  57487. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57488. for (var i = 0; i < this.soundCollection.length; i++) {
  57489. this.soundCollection[i].switchPanningModelToHRTF();
  57490. }
  57491. }
  57492. };
  57493. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  57494. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57495. for (var i = 0; i < this.soundCollection.length; i++) {
  57496. this.soundCollection[i].switchPanningModelToEqualPower();
  57497. }
  57498. }
  57499. };
  57500. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  57501. if (this._connectedAnalyser) {
  57502. this._connectedAnalyser.stopDebugCanvas();
  57503. }
  57504. this._connectedAnalyser = analyser;
  57505. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57506. this._outputAudioNode.disconnect();
  57507. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  57508. }
  57509. };
  57510. return SoundTrack;
  57511. }());
  57512. BABYLON.SoundTrack = SoundTrack;
  57513. })(BABYLON || (BABYLON = {}));
  57514. //# sourceMappingURL=babylon.soundtrack.js.map
  57515. var BABYLON;
  57516. (function (BABYLON) {
  57517. var Analyser = /** @class */ (function () {
  57518. function Analyser(scene) {
  57519. this.SMOOTHING = 0.75;
  57520. this.FFT_SIZE = 512;
  57521. this.BARGRAPHAMPLITUDE = 256;
  57522. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  57523. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  57524. this._scene = scene;
  57525. this._audioEngine = BABYLON.Engine.audioEngine;
  57526. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  57527. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  57528. this._webAudioAnalyser.minDecibels = -140;
  57529. this._webAudioAnalyser.maxDecibels = 0;
  57530. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57531. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57532. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  57533. }
  57534. }
  57535. Analyser.prototype.getFrequencyBinCount = function () {
  57536. if (this._audioEngine.canUseWebAudio) {
  57537. return this._webAudioAnalyser.frequencyBinCount;
  57538. }
  57539. else {
  57540. return 0;
  57541. }
  57542. };
  57543. Analyser.prototype.getByteFrequencyData = function () {
  57544. if (this._audioEngine.canUseWebAudio) {
  57545. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57546. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57547. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  57548. }
  57549. return this._byteFreqs;
  57550. };
  57551. Analyser.prototype.getByteTimeDomainData = function () {
  57552. if (this._audioEngine.canUseWebAudio) {
  57553. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57554. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57555. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  57556. }
  57557. return this._byteTime;
  57558. };
  57559. Analyser.prototype.getFloatFrequencyData = function () {
  57560. if (this._audioEngine.canUseWebAudio) {
  57561. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57562. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57563. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  57564. }
  57565. return this._floatFreqs;
  57566. };
  57567. Analyser.prototype.drawDebugCanvas = function () {
  57568. var _this = this;
  57569. if (this._audioEngine.canUseWebAudio) {
  57570. if (!this._debugCanvas) {
  57571. this._debugCanvas = document.createElement("canvas");
  57572. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  57573. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  57574. this._debugCanvas.style.position = "absolute";
  57575. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  57576. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  57577. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  57578. document.body.appendChild(this._debugCanvas);
  57579. this._registerFunc = function () {
  57580. _this.drawDebugCanvas();
  57581. };
  57582. this._scene.registerBeforeRender(this._registerFunc);
  57583. }
  57584. if (this._registerFunc && this._debugCanvasContext) {
  57585. var workingArray = this.getByteFrequencyData();
  57586. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  57587. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  57588. // Draw the frequency domain chart.
  57589. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  57590. var value = workingArray[i];
  57591. var percent = value / this.BARGRAPHAMPLITUDE;
  57592. var height = this.DEBUGCANVASSIZE.height * percent;
  57593. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  57594. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  57595. var hue = i / this.getFrequencyBinCount() * 360;
  57596. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  57597. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  57598. }
  57599. }
  57600. }
  57601. };
  57602. Analyser.prototype.stopDebugCanvas = function () {
  57603. if (this._debugCanvas) {
  57604. if (this._registerFunc) {
  57605. this._scene.unregisterBeforeRender(this._registerFunc);
  57606. this._registerFunc = null;
  57607. }
  57608. document.body.removeChild(this._debugCanvas);
  57609. this._debugCanvas = null;
  57610. this._debugCanvasContext = null;
  57611. }
  57612. };
  57613. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  57614. if (this._audioEngine.canUseWebAudio) {
  57615. inputAudioNode.connect(this._webAudioAnalyser);
  57616. this._webAudioAnalyser.connect(outputAudioNode);
  57617. }
  57618. };
  57619. Analyser.prototype.dispose = function () {
  57620. if (this._audioEngine.canUseWebAudio) {
  57621. this._webAudioAnalyser.disconnect();
  57622. }
  57623. };
  57624. return Analyser;
  57625. }());
  57626. BABYLON.Analyser = Analyser;
  57627. })(BABYLON || (BABYLON = {}));
  57628. //# sourceMappingURL=babylon.analyser.js.map
  57629. var BABYLON;
  57630. (function (BABYLON) {
  57631. var CubeTexture = /** @class */ (function (_super) {
  57632. __extends(CubeTexture, _super);
  57633. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  57634. if (extensions === void 0) { extensions = null; }
  57635. if (noMipmap === void 0) { noMipmap = false; }
  57636. if (files === void 0) { files = null; }
  57637. if (onLoad === void 0) { onLoad = null; }
  57638. if (onError === void 0) { onError = null; }
  57639. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  57640. if (prefiltered === void 0) { prefiltered = false; }
  57641. if (forcedExtension === void 0) { forcedExtension = null; }
  57642. var _this = _super.call(this, scene) || this;
  57643. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  57644. /**
  57645. * Gets or sets the center of the bounding box associated with the cube texture
  57646. * It must define where the camera used to render the texture was set
  57647. */
  57648. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  57649. _this.name = rootUrl;
  57650. _this.url = rootUrl;
  57651. _this._noMipmap = noMipmap;
  57652. _this.hasAlpha = false;
  57653. _this._format = format;
  57654. _this._prefiltered = prefiltered;
  57655. _this.isCube = true;
  57656. _this._textureMatrix = BABYLON.Matrix.Identity();
  57657. if (prefiltered) {
  57658. _this.gammaSpace = false;
  57659. }
  57660. if (!rootUrl && !files) {
  57661. return _this;
  57662. }
  57663. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  57664. var lastDot = rootUrl.lastIndexOf(".");
  57665. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  57666. var isDDS = (extension === ".dds");
  57667. if (!files) {
  57668. if (!isDDS && !extensions) {
  57669. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  57670. }
  57671. files = [];
  57672. if (extensions) {
  57673. for (var index = 0; index < extensions.length; index++) {
  57674. files.push(rootUrl + extensions[index]);
  57675. }
  57676. }
  57677. }
  57678. _this._files = files;
  57679. if (!_this._texture) {
  57680. if (!scene.useDelayedTextureLoading) {
  57681. if (prefiltered) {
  57682. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  57683. }
  57684. else {
  57685. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  57686. }
  57687. }
  57688. else {
  57689. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  57690. }
  57691. }
  57692. else if (onLoad) {
  57693. if (_this._texture.isReady) {
  57694. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  57695. }
  57696. else {
  57697. _this._texture.onLoadedObservable.add(onLoad);
  57698. }
  57699. }
  57700. return _this;
  57701. }
  57702. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  57703. get: function () {
  57704. return this._boundingBoxSize;
  57705. },
  57706. /**
  57707. * Gets or sets the size of the bounding box associated with the cube texture
  57708. * When defined, the cubemap will switch to local mode
  57709. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  57710. * @example https://www.babylonjs-playground.com/#RNASML
  57711. */
  57712. set: function (value) {
  57713. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  57714. return;
  57715. }
  57716. this._boundingBoxSize = value;
  57717. var scene = this.getScene();
  57718. if (scene) {
  57719. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  57720. }
  57721. },
  57722. enumerable: true,
  57723. configurable: true
  57724. });
  57725. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  57726. var rootUrlKey = "";
  57727. files.forEach(function (url) { return rootUrlKey += url; });
  57728. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  57729. };
  57730. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  57731. if (forcedExtension === void 0) { forcedExtension = null; }
  57732. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  57733. };
  57734. // Methods
  57735. CubeTexture.prototype.delayLoad = function () {
  57736. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  57737. return;
  57738. }
  57739. var scene = this.getScene();
  57740. if (!scene) {
  57741. return;
  57742. }
  57743. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  57744. this._texture = this._getFromCache(this.url, this._noMipmap);
  57745. if (!this._texture) {
  57746. if (this._prefiltered) {
  57747. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  57748. }
  57749. else {
  57750. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  57751. }
  57752. }
  57753. };
  57754. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  57755. return this._textureMatrix;
  57756. };
  57757. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  57758. this._textureMatrix = value;
  57759. };
  57760. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  57761. var texture = BABYLON.SerializationHelper.Parse(function () {
  57762. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  57763. }, parsedTexture, scene);
  57764. // Local Cubemaps
  57765. if (parsedTexture.boundingBoxPosition) {
  57766. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  57767. }
  57768. if (parsedTexture.boundingBoxSize) {
  57769. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  57770. }
  57771. // Animations
  57772. if (parsedTexture.animations) {
  57773. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  57774. var parsedAnimation = parsedTexture.animations[animationIndex];
  57775. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57776. }
  57777. }
  57778. return texture;
  57779. };
  57780. CubeTexture.prototype.clone = function () {
  57781. var _this = this;
  57782. return BABYLON.SerializationHelper.Clone(function () {
  57783. var scene = _this.getScene();
  57784. if (!scene) {
  57785. return _this;
  57786. }
  57787. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  57788. }, this);
  57789. };
  57790. return CubeTexture;
  57791. }(BABYLON.BaseTexture));
  57792. BABYLON.CubeTexture = CubeTexture;
  57793. })(BABYLON || (BABYLON = {}));
  57794. //# sourceMappingURL=babylon.cubeTexture.js.map
  57795. var BABYLON;
  57796. (function (BABYLON) {
  57797. var RenderTargetTexture = /** @class */ (function (_super) {
  57798. __extends(RenderTargetTexture, _super);
  57799. /**
  57800. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  57801. * or used a shadow, depth texture...
  57802. * @param name The friendly name of the texture
  57803. * @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)
  57804. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  57805. * @param generateMipMaps True if mip maps need to be generated after render.
  57806. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  57807. * @param type The type of the buffer in the RTT (int, half float, float...)
  57808. * @param isCube True if a cube texture needs to be created
  57809. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  57810. * @param generateDepthBuffer True to generate a depth buffer
  57811. * @param generateStencilBuffer True to generate a stencil buffer
  57812. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  57813. */
  57814. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  57815. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  57816. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57817. if (isCube === void 0) { isCube = false; }
  57818. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57819. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  57820. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  57821. if (isMulti === void 0) { isMulti = false; }
  57822. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  57823. _this.isCube = isCube;
  57824. /**
  57825. * Use this list to define the list of mesh you want to render.
  57826. */
  57827. _this.renderList = new Array();
  57828. _this.renderParticles = true;
  57829. _this.renderSprites = false;
  57830. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  57831. _this.ignoreCameraViewport = false;
  57832. // Events
  57833. /**
  57834. * An event triggered when the texture is unbind.
  57835. * @type {BABYLON.Observable}
  57836. */
  57837. _this.onBeforeBindObservable = new BABYLON.Observable();
  57838. /**
  57839. * An event triggered when the texture is unbind.
  57840. * @type {BABYLON.Observable}
  57841. */
  57842. _this.onAfterUnbindObservable = new BABYLON.Observable();
  57843. /**
  57844. * An event triggered before rendering the texture
  57845. * @type {BABYLON.Observable}
  57846. */
  57847. _this.onBeforeRenderObservable = new BABYLON.Observable();
  57848. /**
  57849. * An event triggered after rendering the texture
  57850. * @type {BABYLON.Observable}
  57851. */
  57852. _this.onAfterRenderObservable = new BABYLON.Observable();
  57853. /**
  57854. * An event triggered after the texture clear
  57855. * @type {BABYLON.Observable}
  57856. */
  57857. _this.onClearObservable = new BABYLON.Observable();
  57858. _this._currentRefreshId = -1;
  57859. _this._refreshRate = 1;
  57860. _this._samples = 1;
  57861. /**
  57862. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  57863. * It must define where the camera used to render the texture is set
  57864. */
  57865. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  57866. scene = _this.getScene();
  57867. if (!scene) {
  57868. return _this;
  57869. }
  57870. _this._engine = scene.getEngine();
  57871. _this.name = name;
  57872. _this.isRenderTarget = true;
  57873. _this._initialSizeParameter = size;
  57874. _this._processSizeParameter(size);
  57875. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  57876. });
  57877. _this._generateMipMaps = generateMipMaps ? true : false;
  57878. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  57879. // Rendering groups
  57880. _this._renderingManager = new BABYLON.RenderingManager(scene);
  57881. if (isMulti) {
  57882. return _this;
  57883. }
  57884. _this._renderTargetOptions = {
  57885. generateMipMaps: generateMipMaps,
  57886. type: type,
  57887. samplingMode: samplingMode,
  57888. generateDepthBuffer: generateDepthBuffer,
  57889. generateStencilBuffer: generateStencilBuffer
  57890. };
  57891. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  57892. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57893. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57894. }
  57895. if (isCube) {
  57896. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  57897. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  57898. _this._textureMatrix = BABYLON.Matrix.Identity();
  57899. }
  57900. else {
  57901. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  57902. }
  57903. return _this;
  57904. }
  57905. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  57906. get: function () {
  57907. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  57908. },
  57909. enumerable: true,
  57910. configurable: true
  57911. });
  57912. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  57913. get: function () {
  57914. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  57915. },
  57916. enumerable: true,
  57917. configurable: true
  57918. });
  57919. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  57920. get: function () {
  57921. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  57922. },
  57923. enumerable: true,
  57924. configurable: true
  57925. });
  57926. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  57927. set: function (callback) {
  57928. if (this._onAfterUnbindObserver) {
  57929. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  57930. }
  57931. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  57932. },
  57933. enumerable: true,
  57934. configurable: true
  57935. });
  57936. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  57937. set: function (callback) {
  57938. if (this._onBeforeRenderObserver) {
  57939. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  57940. }
  57941. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  57942. },
  57943. enumerable: true,
  57944. configurable: true
  57945. });
  57946. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  57947. set: function (callback) {
  57948. if (this._onAfterRenderObserver) {
  57949. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  57950. }
  57951. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  57952. },
  57953. enumerable: true,
  57954. configurable: true
  57955. });
  57956. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  57957. set: function (callback) {
  57958. if (this._onClearObserver) {
  57959. this.onClearObservable.remove(this._onClearObserver);
  57960. }
  57961. this._onClearObserver = this.onClearObservable.add(callback);
  57962. },
  57963. enumerable: true,
  57964. configurable: true
  57965. });
  57966. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  57967. get: function () {
  57968. return this._renderTargetOptions;
  57969. },
  57970. enumerable: true,
  57971. configurable: true
  57972. });
  57973. RenderTargetTexture.prototype._onRatioRescale = function () {
  57974. if (this._sizeRatio) {
  57975. this.resize(this._initialSizeParameter);
  57976. }
  57977. };
  57978. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  57979. get: function () {
  57980. return this._boundingBoxSize;
  57981. },
  57982. /**
  57983. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  57984. * When defined, the cubemap will switch to local mode
  57985. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  57986. * @example https://www.babylonjs-playground.com/#RNASML
  57987. */
  57988. set: function (value) {
  57989. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  57990. return;
  57991. }
  57992. this._boundingBoxSize = value;
  57993. var scene = this.getScene();
  57994. if (scene) {
  57995. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  57996. }
  57997. },
  57998. enumerable: true,
  57999. configurable: true
  58000. });
  58001. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  58002. if (size.ratio) {
  58003. this._sizeRatio = size.ratio;
  58004. this._size = {
  58005. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  58006. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  58007. };
  58008. }
  58009. else {
  58010. this._size = size;
  58011. }
  58012. };
  58013. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  58014. get: function () {
  58015. return this._samples;
  58016. },
  58017. set: function (value) {
  58018. if (this._samples === value) {
  58019. return;
  58020. }
  58021. var scene = this.getScene();
  58022. if (!scene) {
  58023. return;
  58024. }
  58025. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  58026. },
  58027. enumerable: true,
  58028. configurable: true
  58029. });
  58030. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  58031. this._currentRefreshId = -1;
  58032. };
  58033. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  58034. get: function () {
  58035. return this._refreshRate;
  58036. },
  58037. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  58038. set: function (value) {
  58039. this._refreshRate = value;
  58040. this.resetRefreshCounter();
  58041. },
  58042. enumerable: true,
  58043. configurable: true
  58044. });
  58045. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  58046. if (!this._postProcessManager) {
  58047. var scene = this.getScene();
  58048. if (!scene) {
  58049. return;
  58050. }
  58051. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  58052. this._postProcesses = new Array();
  58053. }
  58054. this._postProcesses.push(postProcess);
  58055. this._postProcesses[0].autoClear = false;
  58056. };
  58057. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  58058. if (!this._postProcesses) {
  58059. return;
  58060. }
  58061. if (dispose) {
  58062. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  58063. var postProcess = _a[_i];
  58064. postProcess.dispose();
  58065. }
  58066. }
  58067. this._postProcesses = [];
  58068. };
  58069. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  58070. if (!this._postProcesses) {
  58071. return;
  58072. }
  58073. var index = this._postProcesses.indexOf(postProcess);
  58074. if (index === -1) {
  58075. return;
  58076. }
  58077. this._postProcesses.splice(index, 1);
  58078. if (this._postProcesses.length > 0) {
  58079. this._postProcesses[0].autoClear = false;
  58080. }
  58081. };
  58082. RenderTargetTexture.prototype._shouldRender = function () {
  58083. if (this._currentRefreshId === -1) {
  58084. this._currentRefreshId = 1;
  58085. return true;
  58086. }
  58087. if (this.refreshRate === this._currentRefreshId) {
  58088. this._currentRefreshId = 1;
  58089. return true;
  58090. }
  58091. this._currentRefreshId++;
  58092. return false;
  58093. };
  58094. RenderTargetTexture.prototype.getRenderSize = function () {
  58095. if (this._size.width) {
  58096. return this._size.width;
  58097. }
  58098. return this._size;
  58099. };
  58100. RenderTargetTexture.prototype.getRenderWidth = function () {
  58101. if (this._size.width) {
  58102. return this._size.width;
  58103. }
  58104. return this._size;
  58105. };
  58106. RenderTargetTexture.prototype.getRenderHeight = function () {
  58107. if (this._size.width) {
  58108. return this._size.height;
  58109. }
  58110. return this._size;
  58111. };
  58112. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  58113. get: function () {
  58114. return true;
  58115. },
  58116. enumerable: true,
  58117. configurable: true
  58118. });
  58119. RenderTargetTexture.prototype.scale = function (ratio) {
  58120. var newSize = this.getRenderSize() * ratio;
  58121. this.resize(newSize);
  58122. };
  58123. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  58124. if (this.isCube) {
  58125. return this._textureMatrix;
  58126. }
  58127. return _super.prototype.getReflectionTextureMatrix.call(this);
  58128. };
  58129. RenderTargetTexture.prototype.resize = function (size) {
  58130. this.releaseInternalTexture();
  58131. var scene = this.getScene();
  58132. if (!scene) {
  58133. return;
  58134. }
  58135. this._processSizeParameter(size);
  58136. if (this.isCube) {
  58137. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  58138. }
  58139. else {
  58140. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  58141. }
  58142. };
  58143. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  58144. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  58145. if (dumpForDebug === void 0) { dumpForDebug = false; }
  58146. var scene = this.getScene();
  58147. if (!scene) {
  58148. return;
  58149. }
  58150. var engine = scene.getEngine();
  58151. if (this.useCameraPostProcesses !== undefined) {
  58152. useCameraPostProcess = this.useCameraPostProcesses;
  58153. }
  58154. if (this._waitingRenderList) {
  58155. this.renderList = [];
  58156. for (var index = 0; index < this._waitingRenderList.length; index++) {
  58157. var id = this._waitingRenderList[index];
  58158. var mesh_1 = scene.getMeshByID(id);
  58159. if (mesh_1) {
  58160. this.renderList.push(mesh_1);
  58161. }
  58162. }
  58163. delete this._waitingRenderList;
  58164. }
  58165. // Is predicate defined?
  58166. if (this.renderListPredicate) {
  58167. if (this.renderList) {
  58168. this.renderList.splice(0); // Clear previous renderList
  58169. }
  58170. else {
  58171. this.renderList = [];
  58172. }
  58173. var scene = this.getScene();
  58174. if (!scene) {
  58175. return;
  58176. }
  58177. var sceneMeshes = scene.meshes;
  58178. for (var index = 0; index < sceneMeshes.length; index++) {
  58179. var mesh = sceneMeshes[index];
  58180. if (this.renderListPredicate(mesh)) {
  58181. this.renderList.push(mesh);
  58182. }
  58183. }
  58184. }
  58185. this.onBeforeBindObservable.notifyObservers(this);
  58186. // Set custom projection.
  58187. // Needs to be before binding to prevent changing the aspect ratio.
  58188. var camera;
  58189. if (this.activeCamera) {
  58190. camera = this.activeCamera;
  58191. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  58192. if (this.activeCamera !== scene.activeCamera) {
  58193. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  58194. }
  58195. }
  58196. else {
  58197. camera = scene.activeCamera;
  58198. if (camera) {
  58199. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  58200. }
  58201. }
  58202. // Prepare renderingManager
  58203. this._renderingManager.reset();
  58204. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  58205. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  58206. var sceneRenderId = scene.getRenderId();
  58207. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  58208. var mesh = currentRenderList[meshIndex];
  58209. if (mesh) {
  58210. if (!mesh.isReady()) {
  58211. // Reset _currentRefreshId
  58212. this.resetRefreshCounter();
  58213. continue;
  58214. }
  58215. mesh._preActivateForIntermediateRendering(sceneRenderId);
  58216. var isMasked = void 0;
  58217. if (!this.renderList && camera) {
  58218. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  58219. }
  58220. else {
  58221. isMasked = false;
  58222. }
  58223. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  58224. mesh._activate(sceneRenderId);
  58225. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  58226. var subMesh = mesh.subMeshes[subIndex];
  58227. scene._activeIndices.addCount(subMesh.indexCount, false);
  58228. this._renderingManager.dispatch(subMesh, mesh);
  58229. }
  58230. }
  58231. }
  58232. }
  58233. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  58234. var particleSystem = scene.particleSystems[particleIndex];
  58235. var emitter = particleSystem.emitter;
  58236. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  58237. continue;
  58238. }
  58239. if (currentRenderList.indexOf(emitter) >= 0) {
  58240. this._renderingManager.dispatchParticles(particleSystem);
  58241. }
  58242. }
  58243. if (this.isCube) {
  58244. for (var face = 0; face < 6; face++) {
  58245. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  58246. scene.incrementRenderId();
  58247. scene.resetCachedMaterial();
  58248. }
  58249. }
  58250. else {
  58251. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  58252. }
  58253. this.onAfterUnbindObservable.notifyObservers(this);
  58254. if (scene.activeCamera) {
  58255. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  58256. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  58257. }
  58258. engine.setViewport(scene.activeCamera.viewport);
  58259. }
  58260. scene.resetCachedMaterial();
  58261. };
  58262. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  58263. var minimum = 128;
  58264. var x = renderDimension * scale;
  58265. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  58266. // Ensure we don't exceed the render dimension (while staying POT)
  58267. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  58268. };
  58269. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  58270. var _this = this;
  58271. if (!this._texture) {
  58272. return;
  58273. }
  58274. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  58275. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  58276. });
  58277. };
  58278. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  58279. var scene = this.getScene();
  58280. if (!scene) {
  58281. return;
  58282. }
  58283. var engine = scene.getEngine();
  58284. if (!this._texture) {
  58285. return;
  58286. }
  58287. // Bind
  58288. if (this._postProcessManager) {
  58289. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  58290. }
  58291. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  58292. if (this._texture) {
  58293. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  58294. }
  58295. }
  58296. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  58297. // Clear
  58298. if (this.onClearObservable.hasObservers()) {
  58299. this.onClearObservable.notifyObservers(engine);
  58300. }
  58301. else {
  58302. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  58303. }
  58304. if (!this._doNotChangeAspectRatio) {
  58305. scene.updateTransformMatrix(true);
  58306. }
  58307. // Render
  58308. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  58309. if (this._postProcessManager) {
  58310. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  58311. }
  58312. else if (useCameraPostProcess) {
  58313. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  58314. }
  58315. if (!this._doNotChangeAspectRatio) {
  58316. scene.updateTransformMatrix(true);
  58317. }
  58318. // Dump ?
  58319. if (dumpForDebug) {
  58320. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  58321. }
  58322. // Unbind
  58323. if (!this.isCube || faceIndex === 5) {
  58324. if (this.isCube) {
  58325. if (faceIndex === 5) {
  58326. engine.generateMipMapsForCubemap(this._texture);
  58327. }
  58328. }
  58329. this.unbindFrameBuffer(engine, faceIndex);
  58330. }
  58331. else {
  58332. this.onAfterRenderObservable.notifyObservers(faceIndex);
  58333. }
  58334. };
  58335. /**
  58336. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  58337. * This allowed control for front to back rendering or reversly depending of the special needs.
  58338. *
  58339. * @param renderingGroupId The rendering group id corresponding to its index
  58340. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  58341. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  58342. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  58343. */
  58344. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  58345. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  58346. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  58347. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  58348. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  58349. };
  58350. /**
  58351. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  58352. *
  58353. * @param renderingGroupId The rendering group id corresponding to its index
  58354. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  58355. */
  58356. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  58357. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  58358. };
  58359. RenderTargetTexture.prototype.clone = function () {
  58360. var textureSize = this.getSize();
  58361. 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);
  58362. // Base texture
  58363. newTexture.hasAlpha = this.hasAlpha;
  58364. newTexture.level = this.level;
  58365. // RenderTarget Texture
  58366. newTexture.coordinatesMode = this.coordinatesMode;
  58367. if (this.renderList) {
  58368. newTexture.renderList = this.renderList.slice(0);
  58369. }
  58370. return newTexture;
  58371. };
  58372. RenderTargetTexture.prototype.serialize = function () {
  58373. if (!this.name) {
  58374. return null;
  58375. }
  58376. var serializationObject = _super.prototype.serialize.call(this);
  58377. serializationObject.renderTargetSize = this.getRenderSize();
  58378. serializationObject.renderList = [];
  58379. if (this.renderList) {
  58380. for (var index = 0; index < this.renderList.length; index++) {
  58381. serializationObject.renderList.push(this.renderList[index].id);
  58382. }
  58383. }
  58384. return serializationObject;
  58385. };
  58386. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  58387. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  58388. var objBuffer = this.getInternalTexture();
  58389. var scene = this.getScene();
  58390. if (objBuffer && scene) {
  58391. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  58392. }
  58393. };
  58394. RenderTargetTexture.prototype.dispose = function () {
  58395. if (this._postProcessManager) {
  58396. this._postProcessManager.dispose();
  58397. this._postProcessManager = null;
  58398. }
  58399. this.clearPostProcesses(true);
  58400. if (this._resizeObserver) {
  58401. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  58402. this._resizeObserver = null;
  58403. }
  58404. this.renderList = null;
  58405. // Remove from custom render targets
  58406. var scene = this.getScene();
  58407. if (!scene) {
  58408. return;
  58409. }
  58410. var index = scene.customRenderTargets.indexOf(this);
  58411. if (index >= 0) {
  58412. scene.customRenderTargets.splice(index, 1);
  58413. }
  58414. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  58415. var camera = _a[_i];
  58416. index = camera.customRenderTargets.indexOf(this);
  58417. if (index >= 0) {
  58418. camera.customRenderTargets.splice(index, 1);
  58419. }
  58420. }
  58421. _super.prototype.dispose.call(this);
  58422. };
  58423. RenderTargetTexture.prototype._rebuild = function () {
  58424. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  58425. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  58426. }
  58427. if (this._postProcessManager) {
  58428. this._postProcessManager._rebuild();
  58429. }
  58430. };
  58431. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  58432. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  58433. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  58434. return RenderTargetTexture;
  58435. }(BABYLON.Texture));
  58436. BABYLON.RenderTargetTexture = RenderTargetTexture;
  58437. })(BABYLON || (BABYLON = {}));
  58438. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  58439. var BABYLON;
  58440. (function (BABYLON) {
  58441. ;
  58442. var MultiRenderTarget = /** @class */ (function (_super) {
  58443. __extends(MultiRenderTarget, _super);
  58444. function MultiRenderTarget(name, size, count, scene, options) {
  58445. var _this = this;
  58446. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  58447. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  58448. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  58449. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  58450. _this._engine = scene.getEngine();
  58451. if (!_this.isSupported) {
  58452. _this.dispose();
  58453. return;
  58454. }
  58455. var types = [];
  58456. var samplingModes = [];
  58457. for (var i = 0; i < count; i++) {
  58458. if (options && options.types && options.types[i] !== undefined) {
  58459. types.push(options.types[i]);
  58460. }
  58461. else {
  58462. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  58463. }
  58464. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  58465. samplingModes.push(options.samplingModes[i]);
  58466. }
  58467. else {
  58468. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58469. }
  58470. }
  58471. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  58472. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  58473. _this._size = size;
  58474. _this._multiRenderTargetOptions = {
  58475. samplingModes: samplingModes,
  58476. generateMipMaps: generateMipMaps,
  58477. generateDepthBuffer: generateDepthBuffer,
  58478. generateStencilBuffer: generateStencilBuffer,
  58479. generateDepthTexture: generateDepthTexture,
  58480. types: types,
  58481. textureCount: count
  58482. };
  58483. _this._createInternalTextures();
  58484. _this._createTextures();
  58485. return _this;
  58486. }
  58487. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  58488. get: function () {
  58489. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  58490. },
  58491. enumerable: true,
  58492. configurable: true
  58493. });
  58494. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  58495. get: function () {
  58496. return this._textures;
  58497. },
  58498. enumerable: true,
  58499. configurable: true
  58500. });
  58501. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  58502. get: function () {
  58503. return this._textures[this._textures.length - 1];
  58504. },
  58505. enumerable: true,
  58506. configurable: true
  58507. });
  58508. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  58509. set: function (wrap) {
  58510. if (this._textures) {
  58511. for (var i = 0; i < this._textures.length; i++) {
  58512. this._textures[i].wrapU = wrap;
  58513. }
  58514. }
  58515. },
  58516. enumerable: true,
  58517. configurable: true
  58518. });
  58519. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  58520. set: function (wrap) {
  58521. if (this._textures) {
  58522. for (var i = 0; i < this._textures.length; i++) {
  58523. this._textures[i].wrapV = wrap;
  58524. }
  58525. }
  58526. },
  58527. enumerable: true,
  58528. configurable: true
  58529. });
  58530. MultiRenderTarget.prototype._rebuild = function () {
  58531. this.releaseInternalTextures();
  58532. this._createInternalTextures();
  58533. for (var i = 0; i < this._internalTextures.length; i++) {
  58534. var texture = this._textures[i];
  58535. texture._texture = this._internalTextures[i];
  58536. }
  58537. // Keeps references to frame buffer and stencil/depth buffer
  58538. this._texture = this._internalTextures[0];
  58539. };
  58540. MultiRenderTarget.prototype._createInternalTextures = function () {
  58541. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  58542. };
  58543. MultiRenderTarget.prototype._createTextures = function () {
  58544. this._textures = [];
  58545. for (var i = 0; i < this._internalTextures.length; i++) {
  58546. var texture = new BABYLON.Texture(null, this.getScene());
  58547. texture._texture = this._internalTextures[i];
  58548. this._textures.push(texture);
  58549. }
  58550. // Keeps references to frame buffer and stencil/depth buffer
  58551. this._texture = this._internalTextures[0];
  58552. };
  58553. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  58554. get: function () {
  58555. return this._samples;
  58556. },
  58557. set: function (value) {
  58558. if (this._samples === value) {
  58559. return;
  58560. }
  58561. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  58562. },
  58563. enumerable: true,
  58564. configurable: true
  58565. });
  58566. MultiRenderTarget.prototype.resize = function (size) {
  58567. this.releaseInternalTextures();
  58568. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  58569. this._createInternalTextures();
  58570. };
  58571. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  58572. var _this = this;
  58573. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  58574. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  58575. });
  58576. };
  58577. MultiRenderTarget.prototype.dispose = function () {
  58578. this.releaseInternalTextures();
  58579. _super.prototype.dispose.call(this);
  58580. };
  58581. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  58582. if (!this._internalTextures) {
  58583. return;
  58584. }
  58585. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  58586. if (this._internalTextures[i] !== undefined) {
  58587. this._internalTextures[i].dispose();
  58588. this._internalTextures.splice(i, 1);
  58589. }
  58590. }
  58591. };
  58592. return MultiRenderTarget;
  58593. }(BABYLON.RenderTargetTexture));
  58594. BABYLON.MultiRenderTarget = MultiRenderTarget;
  58595. })(BABYLON || (BABYLON = {}));
  58596. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  58597. var BABYLON;
  58598. (function (BABYLON) {
  58599. var MirrorTexture = /** @class */ (function (_super) {
  58600. __extends(MirrorTexture, _super);
  58601. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  58602. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58603. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  58604. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  58605. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  58606. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  58607. _this._transformMatrix = BABYLON.Matrix.Zero();
  58608. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  58609. _this._adaptiveBlurKernel = 0;
  58610. _this._blurKernelX = 0;
  58611. _this._blurKernelY = 0;
  58612. _this._blurRatio = 1.0;
  58613. _this.ignoreCameraViewport = true;
  58614. _this.onBeforeRenderObservable.add(function () {
  58615. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  58616. _this._savedViewMatrix = scene.getViewMatrix();
  58617. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  58618. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  58619. scene.clipPlane = _this.mirrorPlane;
  58620. scene.getEngine().cullBackFaces = false;
  58621. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  58622. });
  58623. _this.onAfterRenderObservable.add(function () {
  58624. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  58625. scene.getEngine().cullBackFaces = true;
  58626. scene._mirroredCameraPosition = null;
  58627. delete scene.clipPlane;
  58628. });
  58629. return _this;
  58630. }
  58631. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  58632. get: function () {
  58633. return this._blurRatio;
  58634. },
  58635. set: function (value) {
  58636. if (this._blurRatio === value) {
  58637. return;
  58638. }
  58639. this._blurRatio = value;
  58640. this._preparePostProcesses();
  58641. },
  58642. enumerable: true,
  58643. configurable: true
  58644. });
  58645. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  58646. set: function (value) {
  58647. this._adaptiveBlurKernel = value;
  58648. this._autoComputeBlurKernel();
  58649. },
  58650. enumerable: true,
  58651. configurable: true
  58652. });
  58653. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  58654. set: function (value) {
  58655. this.blurKernelX = value;
  58656. this.blurKernelY = value;
  58657. },
  58658. enumerable: true,
  58659. configurable: true
  58660. });
  58661. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  58662. get: function () {
  58663. return this._blurKernelX;
  58664. },
  58665. set: function (value) {
  58666. if (this._blurKernelX === value) {
  58667. return;
  58668. }
  58669. this._blurKernelX = value;
  58670. this._preparePostProcesses();
  58671. },
  58672. enumerable: true,
  58673. configurable: true
  58674. });
  58675. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  58676. get: function () {
  58677. return this._blurKernelY;
  58678. },
  58679. set: function (value) {
  58680. if (this._blurKernelY === value) {
  58681. return;
  58682. }
  58683. this._blurKernelY = value;
  58684. this._preparePostProcesses();
  58685. },
  58686. enumerable: true,
  58687. configurable: true
  58688. });
  58689. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  58690. var engine = this.getScene().getEngine();
  58691. var dw = this.getRenderWidth() / engine.getRenderWidth();
  58692. var dh = this.getRenderHeight() / engine.getRenderHeight();
  58693. this.blurKernelX = this._adaptiveBlurKernel * dw;
  58694. this.blurKernelY = this._adaptiveBlurKernel * dh;
  58695. };
  58696. MirrorTexture.prototype._onRatioRescale = function () {
  58697. if (this._sizeRatio) {
  58698. this.resize(this._initialSizeParameter);
  58699. if (!this._adaptiveBlurKernel) {
  58700. this._preparePostProcesses();
  58701. }
  58702. }
  58703. if (this._adaptiveBlurKernel) {
  58704. this._autoComputeBlurKernel();
  58705. }
  58706. };
  58707. MirrorTexture.prototype._preparePostProcesses = function () {
  58708. this.clearPostProcesses(true);
  58709. if (this._blurKernelX && this._blurKernelY) {
  58710. var engine = this.getScene().getEngine();
  58711. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58712. 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);
  58713. this._blurX.autoClear = false;
  58714. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  58715. this._blurX.inputTexture = this._texture;
  58716. }
  58717. else {
  58718. this._blurX.alwaysForcePOT = true;
  58719. }
  58720. 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);
  58721. this._blurY.autoClear = false;
  58722. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  58723. this.addPostProcess(this._blurX);
  58724. this.addPostProcess(this._blurY);
  58725. }
  58726. else {
  58727. if (this._blurY) {
  58728. this.removePostProcess(this._blurY);
  58729. this._blurY.dispose();
  58730. this._blurY = null;
  58731. }
  58732. if (this._blurX) {
  58733. this.removePostProcess(this._blurX);
  58734. this._blurX.dispose();
  58735. this._blurX = null;
  58736. }
  58737. }
  58738. };
  58739. MirrorTexture.prototype.clone = function () {
  58740. var scene = this.getScene();
  58741. if (!scene) {
  58742. return this;
  58743. }
  58744. var textureSize = this.getSize();
  58745. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  58746. // Base texture
  58747. newTexture.hasAlpha = this.hasAlpha;
  58748. newTexture.level = this.level;
  58749. // Mirror Texture
  58750. newTexture.mirrorPlane = this.mirrorPlane.clone();
  58751. if (this.renderList) {
  58752. newTexture.renderList = this.renderList.slice(0);
  58753. }
  58754. return newTexture;
  58755. };
  58756. MirrorTexture.prototype.serialize = function () {
  58757. if (!this.name) {
  58758. return null;
  58759. }
  58760. var serializationObject = _super.prototype.serialize.call(this);
  58761. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  58762. return serializationObject;
  58763. };
  58764. return MirrorTexture;
  58765. }(BABYLON.RenderTargetTexture));
  58766. BABYLON.MirrorTexture = MirrorTexture;
  58767. })(BABYLON || (BABYLON = {}));
  58768. //# sourceMappingURL=babylon.mirrorTexture.js.map
  58769. var BABYLON;
  58770. (function (BABYLON) {
  58771. /**
  58772. * Creates a refraction texture used by refraction channel of the standard material.
  58773. * @param name the texture name
  58774. * @param size size of the underlying texture
  58775. * @param scene root scene
  58776. */
  58777. var RefractionTexture = /** @class */ (function (_super) {
  58778. __extends(RefractionTexture, _super);
  58779. function RefractionTexture(name, size, scene, generateMipMaps) {
  58780. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  58781. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  58782. _this.depth = 2.0;
  58783. _this.onBeforeRenderObservable.add(function () {
  58784. scene.clipPlane = _this.refractionPlane;
  58785. });
  58786. _this.onAfterRenderObservable.add(function () {
  58787. delete scene.clipPlane;
  58788. });
  58789. return _this;
  58790. }
  58791. RefractionTexture.prototype.clone = function () {
  58792. var scene = this.getScene();
  58793. if (!scene) {
  58794. return this;
  58795. }
  58796. var textureSize = this.getSize();
  58797. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  58798. // Base texture
  58799. newTexture.hasAlpha = this.hasAlpha;
  58800. newTexture.level = this.level;
  58801. // Refraction Texture
  58802. newTexture.refractionPlane = this.refractionPlane.clone();
  58803. if (this.renderList) {
  58804. newTexture.renderList = this.renderList.slice(0);
  58805. }
  58806. newTexture.depth = this.depth;
  58807. return newTexture;
  58808. };
  58809. RefractionTexture.prototype.serialize = function () {
  58810. if (!this.name) {
  58811. return null;
  58812. }
  58813. var serializationObject = _super.prototype.serialize.call(this);
  58814. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  58815. serializationObject.depth = this.depth;
  58816. return serializationObject;
  58817. };
  58818. return RefractionTexture;
  58819. }(BABYLON.RenderTargetTexture));
  58820. BABYLON.RefractionTexture = RefractionTexture;
  58821. })(BABYLON || (BABYLON = {}));
  58822. //# sourceMappingURL=babylon.refractionTexture.js.map
  58823. var BABYLON;
  58824. (function (BABYLON) {
  58825. var DynamicTexture = /** @class */ (function (_super) {
  58826. __extends(DynamicTexture, _super);
  58827. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  58828. if (scene === void 0) { scene = null; }
  58829. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58830. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  58831. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  58832. _this.name = name;
  58833. _this._engine = _this.getScene().getEngine();
  58834. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58835. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58836. _this._generateMipMaps = generateMipMaps;
  58837. if (options.getContext) {
  58838. _this._canvas = options;
  58839. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  58840. }
  58841. else {
  58842. _this._canvas = document.createElement("canvas");
  58843. if (options.width) {
  58844. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  58845. }
  58846. else {
  58847. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  58848. }
  58849. }
  58850. var textureSize = _this.getSize();
  58851. _this._canvas.width = textureSize.width;
  58852. _this._canvas.height = textureSize.height;
  58853. _this._context = _this._canvas.getContext("2d");
  58854. return _this;
  58855. }
  58856. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  58857. get: function () {
  58858. return true;
  58859. },
  58860. enumerable: true,
  58861. configurable: true
  58862. });
  58863. DynamicTexture.prototype._recreate = function (textureSize) {
  58864. this._canvas.width = textureSize.width;
  58865. this._canvas.height = textureSize.height;
  58866. this.releaseInternalTexture();
  58867. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  58868. };
  58869. DynamicTexture.prototype.scale = function (ratio) {
  58870. var textureSize = this.getSize();
  58871. textureSize.width *= ratio;
  58872. textureSize.height *= ratio;
  58873. this._recreate(textureSize);
  58874. };
  58875. DynamicTexture.prototype.scaleTo = function (width, height) {
  58876. var textureSize = this.getSize();
  58877. textureSize.width = width;
  58878. textureSize.height = height;
  58879. this._recreate(textureSize);
  58880. };
  58881. DynamicTexture.prototype.getContext = function () {
  58882. return this._context;
  58883. };
  58884. DynamicTexture.prototype.clear = function () {
  58885. var size = this.getSize();
  58886. this._context.fillRect(0, 0, size.width, size.height);
  58887. };
  58888. DynamicTexture.prototype.update = function (invertY) {
  58889. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  58890. };
  58891. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  58892. if (update === void 0) { update = true; }
  58893. var size = this.getSize();
  58894. if (clearColor) {
  58895. this._context.fillStyle = clearColor;
  58896. this._context.fillRect(0, 0, size.width, size.height);
  58897. }
  58898. this._context.font = font;
  58899. if (x === null || x === undefined) {
  58900. var textSize = this._context.measureText(text);
  58901. x = (size.width - textSize.width) / 2;
  58902. }
  58903. if (y === null || y === undefined) {
  58904. var fontSize = parseInt((font.replace(/\D/g, '')));
  58905. ;
  58906. y = (size.height / 2) + (fontSize / 3.65);
  58907. }
  58908. this._context.fillStyle = color;
  58909. this._context.fillText(text, x, y);
  58910. if (update) {
  58911. this.update(invertY);
  58912. }
  58913. };
  58914. DynamicTexture.prototype.clone = function () {
  58915. var scene = this.getScene();
  58916. if (!scene) {
  58917. return this;
  58918. }
  58919. var textureSize = this.getSize();
  58920. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  58921. // Base texture
  58922. newTexture.hasAlpha = this.hasAlpha;
  58923. newTexture.level = this.level;
  58924. // Dynamic Texture
  58925. newTexture.wrapU = this.wrapU;
  58926. newTexture.wrapV = this.wrapV;
  58927. return newTexture;
  58928. };
  58929. DynamicTexture.prototype._rebuild = function () {
  58930. this.update();
  58931. };
  58932. return DynamicTexture;
  58933. }(BABYLON.Texture));
  58934. BABYLON.DynamicTexture = DynamicTexture;
  58935. })(BABYLON || (BABYLON = {}));
  58936. //# sourceMappingURL=babylon.dynamicTexture.js.map
  58937. var BABYLON;
  58938. (function (BABYLON) {
  58939. var VideoTexture = /** @class */ (function (_super) {
  58940. __extends(VideoTexture, _super);
  58941. /**
  58942. * Creates a video texture.
  58943. * Sample : https://doc.babylonjs.com/how_to/video_texture
  58944. * @param {string | null} name optional name, will detect from video source, if not defined
  58945. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  58946. * @param {BABYLON.Scene} scene is obviously the current scene.
  58947. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  58948. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  58949. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  58950. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  58951. */
  58952. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  58953. if (generateMipMaps === void 0) { generateMipMaps = false; }
  58954. if (invertY === void 0) { invertY = false; }
  58955. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58956. if (settings === void 0) { settings = {
  58957. autoPlay: true,
  58958. loop: true,
  58959. autoUpdateTexture: true,
  58960. }; }
  58961. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  58962. _this._createInternalTexture = function () {
  58963. if (_this._texture != null) {
  58964. return;
  58965. }
  58966. if (!_this._engine.needPOTTextures ||
  58967. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  58968. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58969. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58970. }
  58971. else {
  58972. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58973. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58974. _this._generateMipMaps = false;
  58975. }
  58976. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  58977. _this._texture.isReady = true;
  58978. _this._updateInternalTexture();
  58979. };
  58980. _this.reset = function () {
  58981. if (_this._texture == null) {
  58982. return;
  58983. }
  58984. _this._texture.dispose();
  58985. _this._texture = null;
  58986. };
  58987. _this._updateInternalTexture = function (e) {
  58988. if (_this._texture == null || !_this._texture.isReady) {
  58989. return;
  58990. }
  58991. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  58992. return;
  58993. }
  58994. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  58995. };
  58996. _this._engine = _this.getScene().getEngine();
  58997. _this._generateMipMaps = generateMipMaps;
  58998. _this._samplingMode = samplingMode;
  58999. _this.autoUpdateTexture = settings.autoUpdateTexture;
  59000. _this.name = name || _this._getName(src);
  59001. _this.video = _this._getVideo(src);
  59002. if (settings.autoPlay !== undefined) {
  59003. _this.video.autoplay = settings.autoPlay;
  59004. }
  59005. if (settings.loop !== undefined) {
  59006. _this.video.loop = settings.loop;
  59007. }
  59008. _this.video.addEventListener("canplay", _this._createInternalTexture);
  59009. _this.video.addEventListener("paused", _this._updateInternalTexture);
  59010. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  59011. _this.video.addEventListener("emptied", _this.reset);
  59012. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  59013. _this._createInternalTexture();
  59014. }
  59015. return _this;
  59016. }
  59017. VideoTexture.prototype._getName = function (src) {
  59018. if (src instanceof HTMLVideoElement) {
  59019. return src.currentSrc;
  59020. }
  59021. if (typeof src === "object") {
  59022. return src.toString();
  59023. }
  59024. return src;
  59025. };
  59026. ;
  59027. VideoTexture.prototype._getVideo = function (src) {
  59028. if (src instanceof HTMLVideoElement) {
  59029. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  59030. return src;
  59031. }
  59032. var video = document.createElement("video");
  59033. if (typeof src === "string") {
  59034. BABYLON.Tools.SetCorsBehavior(src, video);
  59035. video.src = src;
  59036. }
  59037. else {
  59038. BABYLON.Tools.SetCorsBehavior(src[0], video);
  59039. src.forEach(function (url) {
  59040. var source = document.createElement("source");
  59041. source.src = url;
  59042. video.appendChild(source);
  59043. });
  59044. }
  59045. return video;
  59046. };
  59047. ;
  59048. /**
  59049. * Internal method to initiate `update`.
  59050. */
  59051. VideoTexture.prototype._rebuild = function () {
  59052. this.update();
  59053. };
  59054. /**
  59055. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  59056. */
  59057. VideoTexture.prototype.update = function () {
  59058. if (!this.autoUpdateTexture) {
  59059. // Expecting user to call `updateTexture` manually
  59060. return;
  59061. }
  59062. this.updateTexture(true);
  59063. };
  59064. /**
  59065. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  59066. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  59067. */
  59068. VideoTexture.prototype.updateTexture = function (isVisible) {
  59069. if (!isVisible) {
  59070. return;
  59071. }
  59072. if (this.video.paused) {
  59073. return;
  59074. }
  59075. this._updateInternalTexture();
  59076. };
  59077. /**
  59078. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  59079. * @param url New url.
  59080. */
  59081. VideoTexture.prototype.updateURL = function (url) {
  59082. this.video.src = url;
  59083. };
  59084. VideoTexture.prototype.dispose = function () {
  59085. _super.prototype.dispose.call(this);
  59086. this.video.removeEventListener("canplay", this._createInternalTexture);
  59087. this.video.removeEventListener("paused", this._updateInternalTexture);
  59088. this.video.removeEventListener("seeked", this._updateInternalTexture);
  59089. this.video.removeEventListener("emptied", this.reset);
  59090. this.video.pause();
  59091. };
  59092. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  59093. var video = document.createElement("video");
  59094. var constraintsDeviceId;
  59095. if (constraints && constraints.deviceId) {
  59096. constraintsDeviceId = {
  59097. exact: constraints.deviceId,
  59098. };
  59099. }
  59100. navigator.getUserMedia =
  59101. navigator.getUserMedia ||
  59102. navigator.webkitGetUserMedia ||
  59103. navigator.mozGetUserMedia ||
  59104. navigator.msGetUserMedia;
  59105. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  59106. if (navigator.getUserMedia) {
  59107. navigator.getUserMedia({
  59108. video: {
  59109. deviceId: constraintsDeviceId,
  59110. width: {
  59111. min: (constraints && constraints.minWidth) || 256,
  59112. max: (constraints && constraints.maxWidth) || 640,
  59113. },
  59114. height: {
  59115. min: (constraints && constraints.minHeight) || 256,
  59116. max: (constraints && constraints.maxHeight) || 480,
  59117. },
  59118. },
  59119. }, function (stream) {
  59120. if (video.mozSrcObject !== undefined) {
  59121. // hack for Firefox < 19
  59122. video.mozSrcObject = stream;
  59123. }
  59124. else {
  59125. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  59126. }
  59127. video.play();
  59128. if (onReady) {
  59129. onReady(new VideoTexture("video", video, scene, true, true));
  59130. }
  59131. }, function (e) {
  59132. BABYLON.Tools.Error(e.name);
  59133. });
  59134. }
  59135. };
  59136. return VideoTexture;
  59137. }(BABYLON.Texture));
  59138. BABYLON.VideoTexture = VideoTexture;
  59139. })(BABYLON || (BABYLON = {}));
  59140. //# sourceMappingURL=babylon.videoTexture.js.map
  59141. var BABYLON;
  59142. (function (BABYLON) {
  59143. var RawTexture = /** @class */ (function (_super) {
  59144. __extends(RawTexture, _super);
  59145. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  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. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59150. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  59151. _this.format = format;
  59152. _this._engine = scene.getEngine();
  59153. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  59154. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59155. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59156. return _this;
  59157. }
  59158. RawTexture.prototype.update = function (data) {
  59159. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  59160. };
  59161. // Statics
  59162. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59163. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59164. if (invertY === void 0) { invertY = false; }
  59165. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59166. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  59167. };
  59168. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59169. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59170. if (invertY === void 0) { invertY = false; }
  59171. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59172. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  59173. };
  59174. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59175. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59176. if (invertY === void 0) { invertY = false; }
  59177. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59178. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  59179. };
  59180. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  59181. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59182. if (invertY === void 0) { invertY = false; }
  59183. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59184. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59185. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  59186. };
  59187. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  59188. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59189. if (invertY === void 0) { invertY = false; }
  59190. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59191. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59192. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  59193. };
  59194. return RawTexture;
  59195. }(BABYLON.Texture));
  59196. BABYLON.RawTexture = RawTexture;
  59197. })(BABYLON || (BABYLON = {}));
  59198. //# sourceMappingURL=babylon.rawTexture.js.map
  59199. var BABYLON;
  59200. (function (BABYLON) {
  59201. /**
  59202. * PostProcess can be used to apply a shader to a texture after it has been rendered
  59203. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  59204. */
  59205. var PostProcess = /** @class */ (function () {
  59206. /**
  59207. * Creates a new instance of @see PostProcess
  59208. * @param name The name of the PostProcess.
  59209. * @param fragmentUrl The url of the fragment shader to be used.
  59210. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  59211. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  59212. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  59213. * @param camera The camera to apply the render pass to.
  59214. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  59215. * @param engine The engine which the post process will be applied. (default: current engine)
  59216. * @param reusable If the post process can be reused on the same frame. (default: false)
  59217. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  59218. * @param textureType Type of textures used when performing the post process. (default: 0)
  59219. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  59220. * @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
  59221. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  59222. */
  59223. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  59224. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  59225. if (defines === void 0) { defines = null; }
  59226. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59227. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  59228. if (blockCompilation === void 0) { blockCompilation = false; }
  59229. this.name = name;
  59230. /**
  59231. * Width of the texture to apply the post process on
  59232. */
  59233. this.width = -1;
  59234. /**
  59235. * Height of the texture to apply the post process on
  59236. */
  59237. this.height = -1;
  59238. /**
  59239. * If the buffer needs to be cleared before applying the post process. (default: true)
  59240. * Should be set to false if shader will overwrite all previous pixels.
  59241. */
  59242. this.autoClear = true;
  59243. /**
  59244. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  59245. */
  59246. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  59247. /**
  59248. * Animations to be used for the post processing
  59249. */
  59250. this.animations = new Array();
  59251. /**
  59252. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  59253. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  59254. */
  59255. this.enablePixelPerfectMode = false;
  59256. /**
  59257. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  59258. */
  59259. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  59260. /**
  59261. * Force textures to be a power of two (default: false)
  59262. */
  59263. this.alwaysForcePOT = false;
  59264. /**
  59265. * Number of sample textures (default: 1)
  59266. */
  59267. this.samples = 1;
  59268. /**
  59269. * Modify the scale of the post process to be the same as the viewport (default: false)
  59270. */
  59271. this.adaptScaleToCurrentViewport = false;
  59272. this._reusable = false;
  59273. /**
  59274. * Smart array of input and output textures for the post process.
  59275. */
  59276. this._textures = new BABYLON.SmartArray(2);
  59277. /**
  59278. * The index in _textures that corresponds to the output texture.
  59279. */
  59280. this._currentRenderTextureInd = 0;
  59281. this._scaleRatio = new BABYLON.Vector2(1, 1);
  59282. this._texelSize = BABYLON.Vector2.Zero();
  59283. // Events
  59284. /**
  59285. * An event triggered when the postprocess is activated.
  59286. * @type {BABYLON.Observable}
  59287. */
  59288. this.onActivateObservable = new BABYLON.Observable();
  59289. /**
  59290. * An event triggered when the postprocess changes its size.
  59291. * @type {BABYLON.Observable}
  59292. */
  59293. this.onSizeChangedObservable = new BABYLON.Observable();
  59294. /**
  59295. * An event triggered when the postprocess applies its effect.
  59296. * @type {BABYLON.Observable}
  59297. */
  59298. this.onApplyObservable = new BABYLON.Observable();
  59299. /**
  59300. * An event triggered before rendering the postprocess
  59301. * @type {BABYLON.Observable}
  59302. */
  59303. this.onBeforeRenderObservable = new BABYLON.Observable();
  59304. /**
  59305. * An event triggered after rendering the postprocess
  59306. * @type {BABYLON.Observable}
  59307. */
  59308. this.onAfterRenderObservable = new BABYLON.Observable();
  59309. if (camera != null) {
  59310. this._camera = camera;
  59311. this._scene = camera.getScene();
  59312. camera.attachPostProcess(this);
  59313. this._engine = this._scene.getEngine();
  59314. this._scene.postProcesses.push(this);
  59315. }
  59316. else if (engine) {
  59317. this._engine = engine;
  59318. this._engine.postProcesses.push(this);
  59319. }
  59320. this._options = options;
  59321. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  59322. this._reusable = reusable || false;
  59323. this._textureType = textureType;
  59324. this._samplers = samplers || [];
  59325. this._samplers.push("textureSampler");
  59326. this._fragmentUrl = fragmentUrl;
  59327. this._vertexUrl = vertexUrl;
  59328. this._parameters = parameters || [];
  59329. this._parameters.push("scale");
  59330. this._indexParameters = indexParameters;
  59331. if (!blockCompilation) {
  59332. this.updateEffect(defines);
  59333. }
  59334. }
  59335. Object.defineProperty(PostProcess.prototype, "onActivate", {
  59336. /**
  59337. * A function that is added to the onActivateObservable
  59338. */
  59339. set: function (callback) {
  59340. if (this._onActivateObserver) {
  59341. this.onActivateObservable.remove(this._onActivateObserver);
  59342. }
  59343. if (callback) {
  59344. this._onActivateObserver = this.onActivateObservable.add(callback);
  59345. }
  59346. },
  59347. enumerable: true,
  59348. configurable: true
  59349. });
  59350. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  59351. /**
  59352. * A function that is added to the onSizeChangedObservable
  59353. */
  59354. set: function (callback) {
  59355. if (this._onSizeChangedObserver) {
  59356. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  59357. }
  59358. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  59359. },
  59360. enumerable: true,
  59361. configurable: true
  59362. });
  59363. Object.defineProperty(PostProcess.prototype, "onApply", {
  59364. /**
  59365. * A function that is added to the onApplyObservable
  59366. */
  59367. set: function (callback) {
  59368. if (this._onApplyObserver) {
  59369. this.onApplyObservable.remove(this._onApplyObserver);
  59370. }
  59371. this._onApplyObserver = this.onApplyObservable.add(callback);
  59372. },
  59373. enumerable: true,
  59374. configurable: true
  59375. });
  59376. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  59377. /**
  59378. * A function that is added to the onBeforeRenderObservable
  59379. */
  59380. set: function (callback) {
  59381. if (this._onBeforeRenderObserver) {
  59382. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  59383. }
  59384. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  59385. },
  59386. enumerable: true,
  59387. configurable: true
  59388. });
  59389. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  59390. /**
  59391. * A function that is added to the onAfterRenderObservable
  59392. */
  59393. set: function (callback) {
  59394. if (this._onAfterRenderObserver) {
  59395. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  59396. }
  59397. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  59398. },
  59399. enumerable: true,
  59400. configurable: true
  59401. });
  59402. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  59403. /**
  59404. * 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
  59405. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  59406. */
  59407. get: function () {
  59408. return this._textures.data[this._currentRenderTextureInd];
  59409. },
  59410. set: function (value) {
  59411. this._forcedOutputTexture = value;
  59412. },
  59413. enumerable: true,
  59414. configurable: true
  59415. });
  59416. /**
  59417. * Gets the camera which post process is applied to.
  59418. * @returns The camera the post process is applied to.
  59419. */
  59420. PostProcess.prototype.getCamera = function () {
  59421. return this._camera;
  59422. };
  59423. Object.defineProperty(PostProcess.prototype, "texelSize", {
  59424. /**
  59425. * Gets the texel size of the postprocess.
  59426. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  59427. */
  59428. get: function () {
  59429. if (this._shareOutputWithPostProcess) {
  59430. return this._shareOutputWithPostProcess.texelSize;
  59431. }
  59432. if (this._forcedOutputTexture) {
  59433. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  59434. }
  59435. return this._texelSize;
  59436. },
  59437. enumerable: true,
  59438. configurable: true
  59439. });
  59440. /**
  59441. * Gets the engine which this post process belongs to.
  59442. * @returns The engine the post process was enabled with.
  59443. */
  59444. PostProcess.prototype.getEngine = function () {
  59445. return this._engine;
  59446. };
  59447. /**
  59448. * The effect that is created when initializing the post process.
  59449. * @returns The created effect corrisponding the the postprocess.
  59450. */
  59451. PostProcess.prototype.getEffect = function () {
  59452. return this._effect;
  59453. };
  59454. /**
  59455. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  59456. * @param postProcess The post process to share the output with.
  59457. * @returns This post process.
  59458. */
  59459. PostProcess.prototype.shareOutputWith = function (postProcess) {
  59460. this._disposeTextures();
  59461. this._shareOutputWithPostProcess = postProcess;
  59462. return this;
  59463. };
  59464. /**
  59465. * Updates the effect with the current post process compile time values and recompiles the shader.
  59466. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  59467. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  59468. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  59469. * @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
  59470. * @param onCompiled Called when the shader has been compiled.
  59471. * @param onError Called if there is an error when compiling a shader.
  59472. */
  59473. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  59474. if (defines === void 0) { defines = null; }
  59475. if (uniforms === void 0) { uniforms = null; }
  59476. if (samplers === void 0) { samplers = null; }
  59477. 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);
  59478. };
  59479. /**
  59480. * The post process is reusable if it can be used multiple times within one frame.
  59481. * @returns If the post process is reusable
  59482. */
  59483. PostProcess.prototype.isReusable = function () {
  59484. return this._reusable;
  59485. };
  59486. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  59487. PostProcess.prototype.markTextureDirty = function () {
  59488. this.width = -1;
  59489. };
  59490. /**
  59491. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  59492. * 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.
  59493. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  59494. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  59495. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  59496. */
  59497. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  59498. var _this = this;
  59499. if (sourceTexture === void 0) { sourceTexture = null; }
  59500. camera = camera || this._camera;
  59501. var scene = camera.getScene();
  59502. var engine = scene.getEngine();
  59503. var maxSize = engine.getCaps().maxTextureSize;
  59504. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  59505. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  59506. // If rendering to a webvr camera's left or right eye only half the width should be used to avoid resize when rendered to screen
  59507. var webVRCamera = camera.parent;
  59508. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  59509. requiredWidth /= 2;
  59510. }
  59511. var desiredWidth = (this._options.width || requiredWidth);
  59512. var desiredHeight = this._options.height || requiredHeight;
  59513. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  59514. if (this.adaptScaleToCurrentViewport) {
  59515. var currentViewport = engine.currentViewport;
  59516. if (currentViewport) {
  59517. desiredWidth *= currentViewport.width;
  59518. desiredHeight *= currentViewport.height;
  59519. }
  59520. }
  59521. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  59522. if (!this._options.width) {
  59523. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  59524. }
  59525. if (!this._options.height) {
  59526. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  59527. }
  59528. }
  59529. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  59530. if (this._textures.length > 0) {
  59531. for (var i = 0; i < this._textures.length; i++) {
  59532. this._engine._releaseTexture(this._textures.data[i]);
  59533. }
  59534. this._textures.reset();
  59535. }
  59536. this.width = desiredWidth;
  59537. this.height = desiredHeight;
  59538. var textureSize = { width: this.width, height: this.height };
  59539. var textureOptions = {
  59540. generateMipMaps: false,
  59541. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  59542. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  59543. samplingMode: this.renderTargetSamplingMode,
  59544. type: this._textureType
  59545. };
  59546. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  59547. if (this._reusable) {
  59548. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  59549. }
  59550. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  59551. this.onSizeChangedObservable.notifyObservers(this);
  59552. }
  59553. this._textures.forEach(function (texture) {
  59554. if (texture.samples !== _this.samples) {
  59555. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  59556. }
  59557. });
  59558. }
  59559. var target;
  59560. if (this._shareOutputWithPostProcess) {
  59561. target = this._shareOutputWithPostProcess.inputTexture;
  59562. }
  59563. else if (this._forcedOutputTexture) {
  59564. target = this._forcedOutputTexture;
  59565. this.width = this._forcedOutputTexture.width;
  59566. this.height = this._forcedOutputTexture.height;
  59567. }
  59568. else {
  59569. target = this.inputTexture;
  59570. }
  59571. // Bind the input of this post process to be used as the output of the previous post process.
  59572. if (this.enablePixelPerfectMode) {
  59573. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  59574. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  59575. }
  59576. else {
  59577. this._scaleRatio.copyFromFloats(1, 1);
  59578. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  59579. }
  59580. this.onActivateObservable.notifyObservers(camera);
  59581. // Clear
  59582. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  59583. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  59584. }
  59585. if (this._reusable) {
  59586. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  59587. }
  59588. };
  59589. Object.defineProperty(PostProcess.prototype, "isSupported", {
  59590. /**
  59591. * If the post process is supported.
  59592. */
  59593. get: function () {
  59594. return this._effect.isSupported;
  59595. },
  59596. enumerable: true,
  59597. configurable: true
  59598. });
  59599. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  59600. /**
  59601. * The aspect ratio of the output texture.
  59602. */
  59603. get: function () {
  59604. if (this._shareOutputWithPostProcess) {
  59605. return this._shareOutputWithPostProcess.aspectRatio;
  59606. }
  59607. if (this._forcedOutputTexture) {
  59608. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  59609. }
  59610. return this.width / this.height;
  59611. },
  59612. enumerable: true,
  59613. configurable: true
  59614. });
  59615. /**
  59616. * Get a value indicating if the post-process is ready to be used
  59617. * @returns true if the post-process is ready (shader is compiled)
  59618. */
  59619. PostProcess.prototype.isReady = function () {
  59620. return this._effect && this._effect.isReady();
  59621. };
  59622. /**
  59623. * Binds all textures and uniforms to the shader, this will be run on every pass.
  59624. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  59625. */
  59626. PostProcess.prototype.apply = function () {
  59627. // Check
  59628. if (!this._effect || !this._effect.isReady())
  59629. return null;
  59630. // States
  59631. this._engine.enableEffect(this._effect);
  59632. this._engine.setState(false);
  59633. this._engine.setDepthBuffer(false);
  59634. this._engine.setDepthWrite(false);
  59635. // Alpha
  59636. this._engine.setAlphaMode(this.alphaMode);
  59637. if (this.alphaConstants) {
  59638. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  59639. }
  59640. // Bind the output texture of the preivous post process as the input to this post process.
  59641. var source;
  59642. if (this._shareOutputWithPostProcess) {
  59643. source = this._shareOutputWithPostProcess.inputTexture;
  59644. }
  59645. else if (this._forcedOutputTexture) {
  59646. source = this._forcedOutputTexture;
  59647. }
  59648. else {
  59649. source = this.inputTexture;
  59650. }
  59651. this._effect._bindTexture("textureSampler", source);
  59652. // Parameters
  59653. this._effect.setVector2("scale", this._scaleRatio);
  59654. this.onApplyObservable.notifyObservers(this._effect);
  59655. return this._effect;
  59656. };
  59657. PostProcess.prototype._disposeTextures = function () {
  59658. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  59659. return;
  59660. }
  59661. if (this._textures.length > 0) {
  59662. for (var i = 0; i < this._textures.length; i++) {
  59663. this._engine._releaseTexture(this._textures.data[i]);
  59664. }
  59665. }
  59666. this._textures.dispose();
  59667. };
  59668. /**
  59669. * Disposes the post process.
  59670. * @param camera The camera to dispose the post process on.
  59671. */
  59672. PostProcess.prototype.dispose = function (camera) {
  59673. camera = camera || this._camera;
  59674. this._disposeTextures();
  59675. if (this._scene) {
  59676. var index_1 = this._scene.postProcesses.indexOf(this);
  59677. if (index_1 !== -1) {
  59678. this._scene.postProcesses.splice(index_1, 1);
  59679. }
  59680. }
  59681. else {
  59682. var index_2 = this._engine.postProcesses.indexOf(this);
  59683. if (index_2 !== -1) {
  59684. this._engine.postProcesses.splice(index_2, 1);
  59685. }
  59686. }
  59687. if (!camera) {
  59688. return;
  59689. }
  59690. camera.detachPostProcess(this);
  59691. var index = camera._postProcesses.indexOf(this);
  59692. if (index === 0 && camera._postProcesses.length > 0) {
  59693. this._camera._postProcesses[0].markTextureDirty();
  59694. }
  59695. this.onActivateObservable.clear();
  59696. this.onAfterRenderObservable.clear();
  59697. this.onApplyObservable.clear();
  59698. this.onBeforeRenderObservable.clear();
  59699. this.onSizeChangedObservable.clear();
  59700. };
  59701. return PostProcess;
  59702. }());
  59703. BABYLON.PostProcess = PostProcess;
  59704. })(BABYLON || (BABYLON = {}));
  59705. //# sourceMappingURL=babylon.postProcess.js.map
  59706. var BABYLON;
  59707. (function (BABYLON) {
  59708. var PassPostProcess = /** @class */ (function (_super) {
  59709. __extends(PassPostProcess, _super);
  59710. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59711. if (camera === void 0) { camera = null; }
  59712. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59713. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  59714. }
  59715. return PassPostProcess;
  59716. }(BABYLON.PostProcess));
  59717. BABYLON.PassPostProcess = PassPostProcess;
  59718. })(BABYLON || (BABYLON = {}));
  59719. //# sourceMappingURL=babylon.passPostProcess.js.map
  59720. var __assign = (this && this.__assign) || Object.assign || function(t) {
  59721. for (var s, i = 1, n = arguments.length; i < n; i++) {
  59722. s = arguments[i];
  59723. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  59724. t[p] = s[p];
  59725. }
  59726. return t;
  59727. };
  59728. var BABYLON;
  59729. (function (BABYLON) {
  59730. /**
  59731. * Default implementation of @see IShadowGenerator.
  59732. * This is the main object responsible of generating shadows in the framework.
  59733. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  59734. */
  59735. var ShadowGenerator = /** @class */ (function () {
  59736. /**
  59737. * Creates a ShadowGenerator object.
  59738. * A ShadowGenerator is the required tool to use the shadows.
  59739. * Each light casting shadows needs to use its own ShadowGenerator.
  59740. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  59741. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  59742. * @param light The light object generating the shadows.
  59743. * @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.
  59744. */
  59745. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  59746. this._bias = 0.00005;
  59747. this._blurBoxOffset = 1;
  59748. this._blurScale = 2;
  59749. this._blurKernel = 1;
  59750. this._useKernelBlur = false;
  59751. this._filter = ShadowGenerator.FILTER_NONE;
  59752. this._darkness = 0;
  59753. this._transparencyShadow = false;
  59754. /**
  59755. * Controls the extent to which the shadows fade out at the edge of the frustum
  59756. * Used only by directionals and spots
  59757. */
  59758. this.frustumEdgeFalloff = 0;
  59759. /**
  59760. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  59761. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  59762. * It might on the other hand introduce peter panning.
  59763. */
  59764. this.forceBackFacesOnly = false;
  59765. this._lightDirection = BABYLON.Vector3.Zero();
  59766. this._viewMatrix = BABYLON.Matrix.Zero();
  59767. this._projectionMatrix = BABYLON.Matrix.Zero();
  59768. this._transformMatrix = BABYLON.Matrix.Zero();
  59769. this._currentFaceIndex = 0;
  59770. this._currentFaceIndexCache = 0;
  59771. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  59772. this._mapSize = mapSize;
  59773. this._light = light;
  59774. this._scene = light.getScene();
  59775. light._shadowGenerator = this;
  59776. // Texture type fallback from float to int if not supported.
  59777. var caps = this._scene.getEngine().getCaps();
  59778. if (!useFullFloatFirst) {
  59779. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  59780. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59781. }
  59782. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  59783. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  59784. }
  59785. else {
  59786. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59787. }
  59788. }
  59789. else {
  59790. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  59791. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  59792. }
  59793. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  59794. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59795. }
  59796. else {
  59797. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59798. }
  59799. }
  59800. this._initializeGenerator();
  59801. }
  59802. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  59803. /**
  59804. * Shadow generator mode None: no filtering applied.
  59805. */
  59806. get: function () {
  59807. return ShadowGenerator._FILTER_NONE;
  59808. },
  59809. enumerable: true,
  59810. configurable: true
  59811. });
  59812. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  59813. /**
  59814. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  59815. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  59816. */
  59817. get: function () {
  59818. return ShadowGenerator._FILTER_POISSONSAMPLING;
  59819. },
  59820. enumerable: true,
  59821. configurable: true
  59822. });
  59823. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  59824. /**
  59825. * Shadow generator mode ESM: Exponential Shadow Mapping.
  59826. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59827. */
  59828. get: function () {
  59829. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  59830. },
  59831. enumerable: true,
  59832. configurable: true
  59833. });
  59834. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  59835. /**
  59836. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  59837. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59838. */
  59839. get: function () {
  59840. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  59841. },
  59842. enumerable: true,
  59843. configurable: true
  59844. });
  59845. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  59846. /**
  59847. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  59848. * edge artifacts on steep falloff.
  59849. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59850. */
  59851. get: function () {
  59852. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  59853. },
  59854. enumerable: true,
  59855. configurable: true
  59856. });
  59857. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  59858. /**
  59859. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  59860. * edge artifacts on steep falloff.
  59861. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59862. */
  59863. get: function () {
  59864. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  59865. },
  59866. enumerable: true,
  59867. configurable: true
  59868. });
  59869. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  59870. /**
  59871. * Gets the bias: offset applied on the depth preventing acnea.
  59872. */
  59873. get: function () {
  59874. return this._bias;
  59875. },
  59876. /**
  59877. * Sets the bias: offset applied on the depth preventing acnea.
  59878. */
  59879. set: function (bias) {
  59880. this._bias = bias;
  59881. },
  59882. enumerable: true,
  59883. configurable: true
  59884. });
  59885. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  59886. /**
  59887. * Gets the blur box offset: offset applied during the blur pass.
  59888. * Only usefull if useKernelBlur = false
  59889. */
  59890. get: function () {
  59891. return this._blurBoxOffset;
  59892. },
  59893. /**
  59894. * Sets the blur box offset: offset applied during the blur pass.
  59895. * Only usefull if useKernelBlur = false
  59896. */
  59897. set: function (value) {
  59898. if (this._blurBoxOffset === value) {
  59899. return;
  59900. }
  59901. this._blurBoxOffset = value;
  59902. this._disposeBlurPostProcesses();
  59903. },
  59904. enumerable: true,
  59905. configurable: true
  59906. });
  59907. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  59908. /**
  59909. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  59910. * 2 means half of the size.
  59911. */
  59912. get: function () {
  59913. return this._blurScale;
  59914. },
  59915. /**
  59916. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  59917. * 2 means half of the size.
  59918. */
  59919. set: function (value) {
  59920. if (this._blurScale === value) {
  59921. return;
  59922. }
  59923. this._blurScale = value;
  59924. this._disposeBlurPostProcesses();
  59925. },
  59926. enumerable: true,
  59927. configurable: true
  59928. });
  59929. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  59930. /**
  59931. * Gets the blur kernel: kernel size of the blur pass.
  59932. * Only usefull if useKernelBlur = true
  59933. */
  59934. get: function () {
  59935. return this._blurKernel;
  59936. },
  59937. /**
  59938. * Sets the blur kernel: kernel size of the blur pass.
  59939. * Only usefull if useKernelBlur = true
  59940. */
  59941. set: function (value) {
  59942. if (this._blurKernel === value) {
  59943. return;
  59944. }
  59945. this._blurKernel = value;
  59946. this._disposeBlurPostProcesses();
  59947. },
  59948. enumerable: true,
  59949. configurable: true
  59950. });
  59951. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  59952. /**
  59953. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  59954. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  59955. */
  59956. get: function () {
  59957. return this._useKernelBlur;
  59958. },
  59959. /**
  59960. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  59961. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  59962. */
  59963. set: function (value) {
  59964. if (this._useKernelBlur === value) {
  59965. return;
  59966. }
  59967. this._useKernelBlur = value;
  59968. this._disposeBlurPostProcesses();
  59969. },
  59970. enumerable: true,
  59971. configurable: true
  59972. });
  59973. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  59974. /**
  59975. * Gets the depth scale used in ESM mode.
  59976. */
  59977. get: function () {
  59978. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  59979. },
  59980. /**
  59981. * Sets the depth scale used in ESM mode.
  59982. * This can override the scale stored on the light.
  59983. */
  59984. set: function (value) {
  59985. this._depthScale = value;
  59986. },
  59987. enumerable: true,
  59988. configurable: true
  59989. });
  59990. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  59991. /**
  59992. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  59993. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  59994. */
  59995. get: function () {
  59996. return this._filter;
  59997. },
  59998. /**
  59999. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  60000. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  60001. */
  60002. set: function (value) {
  60003. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  60004. if (this._light.needCube()) {
  60005. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  60006. this.useExponentialShadowMap = true;
  60007. return;
  60008. }
  60009. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  60010. this.useCloseExponentialShadowMap = true;
  60011. return;
  60012. }
  60013. }
  60014. if (this._filter === value) {
  60015. return;
  60016. }
  60017. this._filter = value;
  60018. this._disposeBlurPostProcesses();
  60019. this._applyFilterValues();
  60020. this._light._markMeshesAsLightDirty();
  60021. },
  60022. enumerable: true,
  60023. configurable: true
  60024. });
  60025. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  60026. /**
  60027. * Gets if the current filter is set to Poisson Sampling aka PCF.
  60028. */
  60029. get: function () {
  60030. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  60031. },
  60032. /**
  60033. * Sets the current filter to Poisson Sampling aka PCF.
  60034. */
  60035. set: function (value) {
  60036. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  60037. return;
  60038. }
  60039. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  60040. },
  60041. enumerable: true,
  60042. configurable: true
  60043. });
  60044. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  60045. /**
  60046. * Gets if the current filter is set to VSM.
  60047. * DEPRECATED. Should use useExponentialShadowMap instead.
  60048. */
  60049. get: function () {
  60050. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  60051. return this.useExponentialShadowMap;
  60052. },
  60053. /**
  60054. * Sets the current filter is to VSM.
  60055. * DEPRECATED. Should use useExponentialShadowMap instead.
  60056. */
  60057. set: function (value) {
  60058. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  60059. this.useExponentialShadowMap = value;
  60060. },
  60061. enumerable: true,
  60062. configurable: true
  60063. });
  60064. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  60065. /**
  60066. * Gets if the current filter is set to blurred VSM.
  60067. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  60068. */
  60069. get: function () {
  60070. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  60071. return this.useBlurExponentialShadowMap;
  60072. },
  60073. /**
  60074. * Sets the current filter is to blurred VSM.
  60075. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  60076. */
  60077. set: function (value) {
  60078. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  60079. this.useBlurExponentialShadowMap = value;
  60080. },
  60081. enumerable: true,
  60082. configurable: true
  60083. });
  60084. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  60085. /**
  60086. * Gets if the current filter is set to ESM.
  60087. */
  60088. get: function () {
  60089. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  60090. },
  60091. /**
  60092. * Sets the current filter is to ESM.
  60093. */
  60094. set: function (value) {
  60095. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  60096. return;
  60097. }
  60098. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60099. },
  60100. enumerable: true,
  60101. configurable: true
  60102. });
  60103. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  60104. /**
  60105. * Gets if the current filter is set to filtered ESM.
  60106. */
  60107. get: function () {
  60108. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  60109. },
  60110. /**
  60111. * Gets if the current filter is set to filtered ESM.
  60112. */
  60113. set: function (value) {
  60114. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  60115. return;
  60116. }
  60117. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60118. },
  60119. enumerable: true,
  60120. configurable: true
  60121. });
  60122. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  60123. /**
  60124. * Gets if the current filter is set to "close ESM" (using the inverse of the
  60125. * exponential to prevent steep falloff artifacts).
  60126. */
  60127. get: function () {
  60128. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  60129. },
  60130. /**
  60131. * Sets the current filter to "close ESM" (using the inverse of the
  60132. * exponential to prevent steep falloff artifacts).
  60133. */
  60134. set: function (value) {
  60135. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  60136. return;
  60137. }
  60138. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60139. },
  60140. enumerable: true,
  60141. configurable: true
  60142. });
  60143. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  60144. /**
  60145. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  60146. * exponential to prevent steep falloff artifacts).
  60147. */
  60148. get: function () {
  60149. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  60150. },
  60151. /**
  60152. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  60153. * exponential to prevent steep falloff artifacts).
  60154. */
  60155. set: function (value) {
  60156. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  60157. return;
  60158. }
  60159. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60160. },
  60161. enumerable: true,
  60162. configurable: true
  60163. });
  60164. /**
  60165. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  60166. * 0 means strongest and 1 would means no shadow.
  60167. * @returns the darkness.
  60168. */
  60169. ShadowGenerator.prototype.getDarkness = function () {
  60170. return this._darkness;
  60171. };
  60172. /**
  60173. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  60174. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  60175. * @returns the shadow generator allowing fluent coding.
  60176. */
  60177. ShadowGenerator.prototype.setDarkness = function (darkness) {
  60178. if (darkness >= 1.0)
  60179. this._darkness = 1.0;
  60180. else if (darkness <= 0.0)
  60181. this._darkness = 0.0;
  60182. else
  60183. this._darkness = darkness;
  60184. return this;
  60185. };
  60186. /**
  60187. * Sets the ability to have transparent shadow (boolean).
  60188. * @param transparent True if transparent else False
  60189. * @returns the shadow generator allowing fluent coding
  60190. */
  60191. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  60192. this._transparencyShadow = transparent;
  60193. return this;
  60194. };
  60195. /**
  60196. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  60197. * @returns The render target texture if present otherwise, null
  60198. */
  60199. ShadowGenerator.prototype.getShadowMap = function () {
  60200. return this._shadowMap;
  60201. };
  60202. /**
  60203. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  60204. * @returns The render target texture if the shadow map is present otherwise, null
  60205. */
  60206. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  60207. if (this._shadowMap2) {
  60208. return this._shadowMap2;
  60209. }
  60210. return this._shadowMap;
  60211. };
  60212. /**
  60213. * Helper function to add a mesh and its descendants to the list of shadow casters.
  60214. * @param mesh Mesh to add
  60215. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  60216. * @returns the Shadow Generator itself
  60217. */
  60218. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  60219. if (includeDescendants === void 0) { includeDescendants = true; }
  60220. if (!this._shadowMap) {
  60221. return this;
  60222. }
  60223. if (!this._shadowMap.renderList) {
  60224. this._shadowMap.renderList = [];
  60225. }
  60226. this._shadowMap.renderList.push(mesh);
  60227. if (includeDescendants) {
  60228. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  60229. }
  60230. return this;
  60231. var _a;
  60232. };
  60233. /**
  60234. * Helper function to remove a mesh and its descendants from the list of shadow casters
  60235. * @param mesh Mesh to remove
  60236. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  60237. * @returns the Shadow Generator itself
  60238. */
  60239. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  60240. if (includeDescendants === void 0) { includeDescendants = true; }
  60241. if (!this._shadowMap || !this._shadowMap.renderList) {
  60242. return this;
  60243. }
  60244. var index = this._shadowMap.renderList.indexOf(mesh);
  60245. if (index !== -1) {
  60246. this._shadowMap.renderList.splice(index, 1);
  60247. }
  60248. if (includeDescendants) {
  60249. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  60250. var child = _a[_i];
  60251. this.removeShadowCaster(child);
  60252. }
  60253. }
  60254. return this;
  60255. };
  60256. /**
  60257. * Returns the associated light object.
  60258. * @returns the light generating the shadow
  60259. */
  60260. ShadowGenerator.prototype.getLight = function () {
  60261. return this._light;
  60262. };
  60263. ShadowGenerator.prototype._initializeGenerator = function () {
  60264. this._light._markMeshesAsLightDirty();
  60265. this._initializeShadowMap();
  60266. };
  60267. ShadowGenerator.prototype._initializeShadowMap = function () {
  60268. var _this = this;
  60269. // Render target
  60270. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  60271. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60272. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60273. this._shadowMap.anisotropicFilteringLevel = 1;
  60274. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60275. this._shadowMap.renderParticles = false;
  60276. this._shadowMap.ignoreCameraViewport = true;
  60277. // Record Face Index before render.
  60278. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  60279. _this._currentFaceIndex = faceIndex;
  60280. });
  60281. // Custom render function.
  60282. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  60283. // Blur if required afer render.
  60284. this._shadowMap.onAfterUnbindObservable.add(function () {
  60285. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  60286. return;
  60287. }
  60288. var shadowMap = _this.getShadowMapForRendering();
  60289. if (shadowMap) {
  60290. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  60291. }
  60292. });
  60293. // Clear according to the chosen filter.
  60294. this._shadowMap.onClearObservable.add(function (engine) {
  60295. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  60296. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  60297. }
  60298. else {
  60299. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  60300. }
  60301. });
  60302. };
  60303. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  60304. var _this = this;
  60305. var engine = this._scene.getEngine();
  60306. var targetSize = this._mapSize / this.blurScale;
  60307. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  60308. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  60309. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60310. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60311. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60312. }
  60313. if (this.useKernelBlur) {
  60314. 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);
  60315. this._kernelBlurXPostprocess.width = targetSize;
  60316. this._kernelBlurXPostprocess.height = targetSize;
  60317. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  60318. effect.setTexture("textureSampler", _this._shadowMap);
  60319. });
  60320. 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);
  60321. this._kernelBlurXPostprocess.autoClear = false;
  60322. this._kernelBlurYPostprocess.autoClear = false;
  60323. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  60324. this._kernelBlurXPostprocess.packedFloat = true;
  60325. this._kernelBlurYPostprocess.packedFloat = true;
  60326. }
  60327. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  60328. }
  60329. else {
  60330. 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);
  60331. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  60332. effect.setFloat2("screenSize", targetSize, targetSize);
  60333. effect.setTexture("textureSampler", _this._shadowMap);
  60334. });
  60335. this._boxBlurPostprocess.autoClear = false;
  60336. this._blurPostProcesses = [this._boxBlurPostprocess];
  60337. }
  60338. };
  60339. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  60340. var index;
  60341. var engine = this._scene.getEngine();
  60342. if (depthOnlySubMeshes.length) {
  60343. engine.setColorWrite(false);
  60344. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  60345. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  60346. }
  60347. engine.setColorWrite(true);
  60348. }
  60349. for (index = 0; index < opaqueSubMeshes.length; index++) {
  60350. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  60351. }
  60352. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  60353. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  60354. }
  60355. if (this._transparencyShadow) {
  60356. for (index = 0; index < transparentSubMeshes.length; index++) {
  60357. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  60358. }
  60359. }
  60360. };
  60361. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  60362. var _this = this;
  60363. var mesh = subMesh.getRenderingMesh();
  60364. var scene = this._scene;
  60365. var engine = scene.getEngine();
  60366. var material = subMesh.getMaterial();
  60367. if (!material) {
  60368. return;
  60369. }
  60370. // Culling
  60371. engine.setState(material.backFaceCulling);
  60372. // Managing instances
  60373. var batch = mesh._getInstancesRenderList(subMesh._id);
  60374. if (batch.mustReturn) {
  60375. return;
  60376. }
  60377. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  60378. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  60379. engine.enableEffect(this._effect);
  60380. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  60381. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  60382. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  60383. this._effect.setVector3("lightPosition", this.getLight().position);
  60384. if (scene.activeCamera) {
  60385. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  60386. }
  60387. // Alpha test
  60388. if (material && material.needAlphaTesting()) {
  60389. var alphaTexture = material.getAlphaTestTexture();
  60390. if (alphaTexture) {
  60391. this._effect.setTexture("diffuseSampler", alphaTexture);
  60392. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  60393. }
  60394. }
  60395. // Bones
  60396. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60397. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  60398. }
  60399. if (this.forceBackFacesOnly) {
  60400. engine.setState(true, 0, false, true);
  60401. }
  60402. // Draw
  60403. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  60404. if (this.forceBackFacesOnly) {
  60405. engine.setState(true, 0, false, false);
  60406. }
  60407. }
  60408. else {
  60409. // Need to reset refresh rate of the shadowMap
  60410. if (this._shadowMap) {
  60411. this._shadowMap.resetRefreshCounter();
  60412. }
  60413. }
  60414. };
  60415. ShadowGenerator.prototype._applyFilterValues = function () {
  60416. if (!this._shadowMap) {
  60417. return;
  60418. }
  60419. if (this.filter === ShadowGenerator.FILTER_NONE) {
  60420. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  60421. }
  60422. else {
  60423. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60424. }
  60425. };
  60426. /**
  60427. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  60428. * @param onCompiled Callback triggered at the and of the effects compilation
  60429. * @param options Sets of optional options forcing the compilation with different modes
  60430. */
  60431. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  60432. var _this = this;
  60433. var localOptions = __assign({ useInstances: false }, options);
  60434. var shadowMap = this.getShadowMap();
  60435. if (!shadowMap) {
  60436. if (onCompiled) {
  60437. onCompiled(this);
  60438. }
  60439. return;
  60440. }
  60441. var renderList = shadowMap.renderList;
  60442. if (!renderList) {
  60443. if (onCompiled) {
  60444. onCompiled(this);
  60445. }
  60446. return;
  60447. }
  60448. var subMeshes = new Array();
  60449. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  60450. var mesh = renderList_1[_i];
  60451. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  60452. }
  60453. if (subMeshes.length === 0) {
  60454. if (onCompiled) {
  60455. onCompiled(this);
  60456. }
  60457. return;
  60458. }
  60459. var currentIndex = 0;
  60460. var checkReady = function () {
  60461. if (!_this._scene || !_this._scene.getEngine()) {
  60462. return;
  60463. }
  60464. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  60465. currentIndex++;
  60466. if (currentIndex >= subMeshes.length) {
  60467. if (onCompiled) {
  60468. onCompiled(_this);
  60469. }
  60470. return;
  60471. }
  60472. }
  60473. setTimeout(checkReady, 16);
  60474. };
  60475. checkReady();
  60476. };
  60477. /**
  60478. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  60479. * @param options Sets of optional options forcing the compilation with different modes
  60480. * @returns A promise that resolves when the compilation completes
  60481. */
  60482. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  60483. var _this = this;
  60484. return new Promise(function (resolve) {
  60485. _this.forceCompilation(function () {
  60486. resolve();
  60487. }, options);
  60488. });
  60489. };
  60490. /**
  60491. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  60492. * @param subMesh The submesh we want to render in the shadow map
  60493. * @param useInstances Defines wether will draw in the map using instances
  60494. * @returns true if ready otherwise, false
  60495. */
  60496. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  60497. var defines = [];
  60498. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  60499. defines.push("#define FLOAT");
  60500. }
  60501. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  60502. defines.push("#define ESM");
  60503. }
  60504. var attribs = [BABYLON.VertexBuffer.PositionKind];
  60505. var mesh = subMesh.getMesh();
  60506. var material = subMesh.getMaterial();
  60507. // Alpha test
  60508. if (material && material.needAlphaTesting()) {
  60509. var alphaTexture = material.getAlphaTestTexture();
  60510. if (alphaTexture) {
  60511. defines.push("#define ALPHATEST");
  60512. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60513. attribs.push(BABYLON.VertexBuffer.UVKind);
  60514. defines.push("#define UV1");
  60515. }
  60516. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60517. if (alphaTexture.coordinatesIndex === 1) {
  60518. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60519. defines.push("#define UV2");
  60520. }
  60521. }
  60522. }
  60523. }
  60524. // Bones
  60525. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60526. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60527. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60528. if (mesh.numBoneInfluencers > 4) {
  60529. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60530. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60531. }
  60532. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60533. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  60534. }
  60535. else {
  60536. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60537. }
  60538. // Instances
  60539. if (useInstances) {
  60540. defines.push("#define INSTANCES");
  60541. attribs.push("world0");
  60542. attribs.push("world1");
  60543. attribs.push("world2");
  60544. attribs.push("world3");
  60545. }
  60546. // Get correct effect
  60547. var join = defines.join("\n");
  60548. if (this._cachedDefines !== join) {
  60549. this._cachedDefines = join;
  60550. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  60551. }
  60552. if (!this._effect.isReady()) {
  60553. return false;
  60554. }
  60555. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  60556. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  60557. this._initializeBlurRTTAndPostProcesses();
  60558. }
  60559. }
  60560. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  60561. return false;
  60562. }
  60563. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  60564. return false;
  60565. }
  60566. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  60567. return false;
  60568. }
  60569. return true;
  60570. };
  60571. /**
  60572. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  60573. * @param defines Defines of the material we want to update
  60574. * @param lightIndex Index of the light in the enabled light list of the material
  60575. */
  60576. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  60577. var scene = this._scene;
  60578. var light = this._light;
  60579. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  60580. return;
  60581. }
  60582. defines["SHADOW" + lightIndex] = true;
  60583. if (this.usePoissonSampling) {
  60584. defines["SHADOWPCF" + lightIndex] = true;
  60585. }
  60586. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  60587. defines["SHADOWESM" + lightIndex] = true;
  60588. }
  60589. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  60590. defines["SHADOWCLOSEESM" + lightIndex] = true;
  60591. }
  60592. if (light.needCube()) {
  60593. defines["SHADOWCUBE" + lightIndex] = true;
  60594. }
  60595. };
  60596. /**
  60597. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  60598. * defined in the generator but impacting the effect).
  60599. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  60600. * @param effect The effect we are binfing the information for
  60601. */
  60602. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  60603. var light = this._light;
  60604. var scene = this._scene;
  60605. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  60606. return;
  60607. }
  60608. var camera = scene.activeCamera;
  60609. if (!camera) {
  60610. return;
  60611. }
  60612. var shadowMap = this.getShadowMap();
  60613. if (!shadowMap) {
  60614. return;
  60615. }
  60616. if (!light.needCube()) {
  60617. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  60618. }
  60619. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  60620. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  60621. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  60622. };
  60623. /**
  60624. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  60625. * (eq to shadow prjection matrix * light transform matrix)
  60626. * @returns The transform matrix used to create the shadow map
  60627. */
  60628. ShadowGenerator.prototype.getTransformMatrix = function () {
  60629. var scene = this._scene;
  60630. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  60631. return this._transformMatrix;
  60632. }
  60633. this._currentRenderID = scene.getRenderId();
  60634. this._currentFaceIndexCache = this._currentFaceIndex;
  60635. var lightPosition = this._light.position;
  60636. if (this._light.computeTransformedInformation()) {
  60637. lightPosition = this._light.transformedPosition;
  60638. }
  60639. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  60640. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  60641. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  60642. }
  60643. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  60644. this._cachedPosition = lightPosition.clone();
  60645. this._cachedDirection = this._lightDirection.clone();
  60646. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  60647. var shadowMap = this.getShadowMap();
  60648. if (shadowMap) {
  60649. var renderList = shadowMap.renderList;
  60650. if (renderList) {
  60651. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  60652. }
  60653. }
  60654. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  60655. }
  60656. return this._transformMatrix;
  60657. };
  60658. /**
  60659. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  60660. * Cube and 2D textures for instance.
  60661. */
  60662. ShadowGenerator.prototype.recreateShadowMap = function () {
  60663. var shadowMap = this._shadowMap;
  60664. if (!shadowMap) {
  60665. return;
  60666. }
  60667. // Track render list.
  60668. var renderList = shadowMap.renderList;
  60669. // Clean up existing data.
  60670. this._disposeRTTandPostProcesses();
  60671. // Reinitializes.
  60672. this._initializeGenerator();
  60673. // Reaffect the filter to ensure a correct fallback if necessary.
  60674. this.filter = this.filter;
  60675. // Reaffect the filter.
  60676. this._applyFilterValues();
  60677. // Reaffect Render List.
  60678. this._shadowMap.renderList = renderList;
  60679. };
  60680. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  60681. if (this._shadowMap2) {
  60682. this._shadowMap2.dispose();
  60683. this._shadowMap2 = null;
  60684. }
  60685. if (this._boxBlurPostprocess) {
  60686. this._boxBlurPostprocess.dispose();
  60687. this._boxBlurPostprocess = null;
  60688. }
  60689. if (this._kernelBlurXPostprocess) {
  60690. this._kernelBlurXPostprocess.dispose();
  60691. this._kernelBlurXPostprocess = null;
  60692. }
  60693. if (this._kernelBlurYPostprocess) {
  60694. this._kernelBlurYPostprocess.dispose();
  60695. this._kernelBlurYPostprocess = null;
  60696. }
  60697. this._blurPostProcesses = [];
  60698. };
  60699. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  60700. if (this._shadowMap) {
  60701. this._shadowMap.dispose();
  60702. this._shadowMap = null;
  60703. }
  60704. this._disposeBlurPostProcesses();
  60705. };
  60706. /**
  60707. * Disposes the ShadowGenerator.
  60708. * Returns nothing.
  60709. */
  60710. ShadowGenerator.prototype.dispose = function () {
  60711. this._disposeRTTandPostProcesses();
  60712. if (this._light) {
  60713. this._light._shadowGenerator = null;
  60714. this._light._markMeshesAsLightDirty();
  60715. }
  60716. };
  60717. /**
  60718. * Serializes the shadow generator setup to a json object.
  60719. * @returns The serialized JSON object
  60720. */
  60721. ShadowGenerator.prototype.serialize = function () {
  60722. var serializationObject = {};
  60723. var shadowMap = this.getShadowMap();
  60724. if (!shadowMap) {
  60725. return serializationObject;
  60726. }
  60727. serializationObject.lightId = this._light.id;
  60728. serializationObject.mapSize = shadowMap.getRenderSize();
  60729. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  60730. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  60731. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  60732. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  60733. serializationObject.usePoissonSampling = this.usePoissonSampling;
  60734. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  60735. serializationObject.depthScale = this.depthScale;
  60736. serializationObject.darkness = this.getDarkness();
  60737. serializationObject.blurBoxOffset = this.blurBoxOffset;
  60738. serializationObject.blurKernel = this.blurKernel;
  60739. serializationObject.blurScale = this.blurScale;
  60740. serializationObject.useKernelBlur = this.useKernelBlur;
  60741. serializationObject.transparencyShadow = this._transparencyShadow;
  60742. serializationObject.renderList = [];
  60743. if (shadowMap.renderList) {
  60744. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  60745. var mesh = shadowMap.renderList[meshIndex];
  60746. serializationObject.renderList.push(mesh.id);
  60747. }
  60748. }
  60749. return serializationObject;
  60750. };
  60751. /**
  60752. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  60753. * @param parsedShadowGenerator The JSON object to parse
  60754. * @param scene The scene to create the shadow map for
  60755. * @returns The parsed shadow generator
  60756. */
  60757. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  60758. //casting to point light, as light is missing the position attr and typescript complains.
  60759. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  60760. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  60761. var shadowMap = shadowGenerator.getShadowMap();
  60762. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  60763. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  60764. meshes.forEach(function (mesh) {
  60765. if (!shadowMap) {
  60766. return;
  60767. }
  60768. if (!shadowMap.renderList) {
  60769. shadowMap.renderList = [];
  60770. }
  60771. shadowMap.renderList.push(mesh);
  60772. });
  60773. }
  60774. if (parsedShadowGenerator.usePoissonSampling) {
  60775. shadowGenerator.usePoissonSampling = true;
  60776. }
  60777. else if (parsedShadowGenerator.useExponentialShadowMap) {
  60778. shadowGenerator.useExponentialShadowMap = true;
  60779. }
  60780. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  60781. shadowGenerator.useBlurExponentialShadowMap = true;
  60782. }
  60783. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  60784. shadowGenerator.useCloseExponentialShadowMap = true;
  60785. }
  60786. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  60787. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  60788. }
  60789. else if (parsedShadowGenerator.useVarianceShadowMap) {
  60790. shadowGenerator.useExponentialShadowMap = true;
  60791. }
  60792. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  60793. shadowGenerator.useBlurExponentialShadowMap = true;
  60794. }
  60795. if (parsedShadowGenerator.depthScale) {
  60796. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  60797. }
  60798. if (parsedShadowGenerator.blurScale) {
  60799. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  60800. }
  60801. if (parsedShadowGenerator.blurBoxOffset) {
  60802. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  60803. }
  60804. if (parsedShadowGenerator.useKernelBlur) {
  60805. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  60806. }
  60807. if (parsedShadowGenerator.blurKernel) {
  60808. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  60809. }
  60810. if (parsedShadowGenerator.bias !== undefined) {
  60811. shadowGenerator.bias = parsedShadowGenerator.bias;
  60812. }
  60813. if (parsedShadowGenerator.darkness) {
  60814. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  60815. }
  60816. if (parsedShadowGenerator.transparencyShadow) {
  60817. shadowGenerator.setTransparencyShadow(true);
  60818. }
  60819. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  60820. return shadowGenerator;
  60821. };
  60822. ShadowGenerator._FILTER_NONE = 0;
  60823. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  60824. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  60825. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  60826. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  60827. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  60828. return ShadowGenerator;
  60829. }());
  60830. BABYLON.ShadowGenerator = ShadowGenerator;
  60831. })(BABYLON || (BABYLON = {}));
  60832. //# sourceMappingURL=babylon.shadowGenerator.js.map
  60833. var BABYLON;
  60834. (function (BABYLON) {
  60835. var DefaultLoadingScreen = /** @class */ (function () {
  60836. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  60837. if (_loadingText === void 0) { _loadingText = ""; }
  60838. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  60839. var _this = this;
  60840. this._renderingCanvas = _renderingCanvas;
  60841. this._loadingText = _loadingText;
  60842. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  60843. // Resize
  60844. this._resizeLoadingUI = function () {
  60845. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  60846. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  60847. if (!_this._loadingDiv) {
  60848. return;
  60849. }
  60850. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  60851. _this._loadingDiv.style.left = canvasRect.left + "px";
  60852. _this._loadingDiv.style.top = canvasRect.top + "px";
  60853. _this._loadingDiv.style.width = canvasRect.width + "px";
  60854. _this._loadingDiv.style.height = canvasRect.height + "px";
  60855. };
  60856. }
  60857. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  60858. if (this._loadingDiv) {
  60859. // Do not add a loading screen if there is already one
  60860. return;
  60861. }
  60862. this._loadingDiv = document.createElement("div");
  60863. this._loadingDiv.id = "babylonjsLoadingDiv";
  60864. this._loadingDiv.style.opacity = "0";
  60865. this._loadingDiv.style.transition = "opacity 1.5s ease";
  60866. this._loadingDiv.style.pointerEvents = "none";
  60867. // Loading text
  60868. this._loadingTextDiv = document.createElement("div");
  60869. this._loadingTextDiv.style.position = "absolute";
  60870. this._loadingTextDiv.style.left = "0";
  60871. this._loadingTextDiv.style.top = "50%";
  60872. this._loadingTextDiv.style.marginTop = "80px";
  60873. this._loadingTextDiv.style.width = "100%";
  60874. this._loadingTextDiv.style.height = "20px";
  60875. this._loadingTextDiv.style.fontFamily = "Arial";
  60876. this._loadingTextDiv.style.fontSize = "14px";
  60877. this._loadingTextDiv.style.color = "white";
  60878. this._loadingTextDiv.style.textAlign = "center";
  60879. this._loadingTextDiv.innerHTML = "Loading";
  60880. this._loadingDiv.appendChild(this._loadingTextDiv);
  60881. //set the predefined text
  60882. this._loadingTextDiv.innerHTML = this._loadingText;
  60883. // Generating keyframes
  60884. var style = document.createElement('style');
  60885. style.type = 'text/css';
  60886. 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 }";
  60887. style.innerHTML = keyFrames;
  60888. document.getElementsByTagName('head')[0].appendChild(style);
  60889. // Loading img
  60890. var imgBack = new Image();
  60891. 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";
  60892. imgBack.style.position = "absolute";
  60893. imgBack.style.left = "50%";
  60894. imgBack.style.top = "50%";
  60895. imgBack.style.marginLeft = "-60px";
  60896. imgBack.style.marginTop = "-60px";
  60897. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  60898. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  60899. imgBack.style.transformOrigin = "50% 50%";
  60900. imgBack.style.webkitTransformOrigin = "50% 50%";
  60901. this._loadingDiv.appendChild(imgBack);
  60902. this._resizeLoadingUI();
  60903. window.addEventListener("resize", this._resizeLoadingUI);
  60904. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  60905. document.body.appendChild(this._loadingDiv);
  60906. this._loadingDiv.style.opacity = "1";
  60907. };
  60908. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  60909. var _this = this;
  60910. if (!this._loadingDiv) {
  60911. return;
  60912. }
  60913. var onTransitionEnd = function () {
  60914. if (!_this._loadingDiv) {
  60915. return;
  60916. }
  60917. document.body.removeChild(_this._loadingDiv);
  60918. window.removeEventListener("resize", _this._resizeLoadingUI);
  60919. _this._loadingDiv = null;
  60920. };
  60921. this._loadingDiv.style.opacity = "0";
  60922. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  60923. };
  60924. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  60925. set: function (text) {
  60926. this._loadingText = text;
  60927. if (this._loadingTextDiv) {
  60928. this._loadingTextDiv.innerHTML = this._loadingText;
  60929. }
  60930. },
  60931. enumerable: true,
  60932. configurable: true
  60933. });
  60934. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  60935. get: function () {
  60936. return this._loadingDivBackgroundColor;
  60937. },
  60938. set: function (color) {
  60939. this._loadingDivBackgroundColor = color;
  60940. if (!this._loadingDiv) {
  60941. return;
  60942. }
  60943. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  60944. },
  60945. enumerable: true,
  60946. configurable: true
  60947. });
  60948. return DefaultLoadingScreen;
  60949. }());
  60950. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  60951. })(BABYLON || (BABYLON = {}));
  60952. //# sourceMappingURL=babylon.loadingScreen.js.map
  60953. var BABYLON;
  60954. (function (BABYLON) {
  60955. var SceneLoaderProgressEvent = /** @class */ (function () {
  60956. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  60957. this.lengthComputable = lengthComputable;
  60958. this.loaded = loaded;
  60959. this.total = total;
  60960. }
  60961. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  60962. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  60963. };
  60964. return SceneLoaderProgressEvent;
  60965. }());
  60966. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  60967. var SceneLoader = /** @class */ (function () {
  60968. function SceneLoader() {
  60969. }
  60970. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  60971. get: function () {
  60972. return 0;
  60973. },
  60974. enumerable: true,
  60975. configurable: true
  60976. });
  60977. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  60978. get: function () {
  60979. return 1;
  60980. },
  60981. enumerable: true,
  60982. configurable: true
  60983. });
  60984. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  60985. get: function () {
  60986. return 2;
  60987. },
  60988. enumerable: true,
  60989. configurable: true
  60990. });
  60991. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  60992. get: function () {
  60993. return 3;
  60994. },
  60995. enumerable: true,
  60996. configurable: true
  60997. });
  60998. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  60999. get: function () {
  61000. return SceneLoader._ForceFullSceneLoadingForIncremental;
  61001. },
  61002. set: function (value) {
  61003. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  61004. },
  61005. enumerable: true,
  61006. configurable: true
  61007. });
  61008. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  61009. get: function () {
  61010. return SceneLoader._ShowLoadingScreen;
  61011. },
  61012. set: function (value) {
  61013. SceneLoader._ShowLoadingScreen = value;
  61014. },
  61015. enumerable: true,
  61016. configurable: true
  61017. });
  61018. Object.defineProperty(SceneLoader, "loggingLevel", {
  61019. get: function () {
  61020. return SceneLoader._loggingLevel;
  61021. },
  61022. set: function (value) {
  61023. SceneLoader._loggingLevel = value;
  61024. },
  61025. enumerable: true,
  61026. configurable: true
  61027. });
  61028. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  61029. get: function () {
  61030. return SceneLoader._CleanBoneMatrixWeights;
  61031. },
  61032. set: function (value) {
  61033. SceneLoader._CleanBoneMatrixWeights = value;
  61034. },
  61035. enumerable: true,
  61036. configurable: true
  61037. });
  61038. SceneLoader._getDefaultPlugin = function () {
  61039. return SceneLoader._registeredPlugins[".babylon"];
  61040. };
  61041. SceneLoader._getPluginForExtension = function (extension) {
  61042. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  61043. if (registeredPlugin) {
  61044. return registeredPlugin;
  61045. }
  61046. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  61047. return SceneLoader._getDefaultPlugin();
  61048. };
  61049. SceneLoader._getPluginForDirectLoad = function (data) {
  61050. for (var extension in SceneLoader._registeredPlugins) {
  61051. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  61052. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  61053. return SceneLoader._registeredPlugins[extension];
  61054. }
  61055. }
  61056. return SceneLoader._getDefaultPlugin();
  61057. };
  61058. SceneLoader._getPluginForFilename = function (sceneFilename) {
  61059. if (sceneFilename.name) {
  61060. sceneFilename = sceneFilename.name;
  61061. }
  61062. var queryStringPosition = sceneFilename.indexOf("?");
  61063. if (queryStringPosition !== -1) {
  61064. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  61065. }
  61066. var dotPosition = sceneFilename.lastIndexOf(".");
  61067. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  61068. return SceneLoader._getPluginForExtension(extension);
  61069. };
  61070. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  61071. SceneLoader._getDirectLoad = function (sceneFilename) {
  61072. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  61073. return sceneFilename.substr(5);
  61074. }
  61075. return null;
  61076. };
  61077. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  61078. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  61079. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  61080. var plugin;
  61081. if (registeredPlugin.plugin.createPlugin) {
  61082. plugin = registeredPlugin.plugin.createPlugin();
  61083. }
  61084. else {
  61085. plugin = registeredPlugin.plugin;
  61086. }
  61087. var useArrayBuffer = registeredPlugin.isBinary;
  61088. var database;
  61089. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  61090. var dataCallback = function (data, responseURL) {
  61091. if (scene.isDisposed) {
  61092. onError("Scene has been disposed");
  61093. return;
  61094. }
  61095. scene.database = database;
  61096. onSuccess(plugin, data, responseURL);
  61097. };
  61098. var request = null;
  61099. var pluginDisposed = false;
  61100. var onDisposeObservable = plugin.onDisposeObservable;
  61101. if (onDisposeObservable) {
  61102. onDisposeObservable.add(function () {
  61103. pluginDisposed = true;
  61104. if (request) {
  61105. request.abort();
  61106. request = null;
  61107. }
  61108. onDispose();
  61109. });
  61110. }
  61111. var manifestChecked = function () {
  61112. if (pluginDisposed) {
  61113. return;
  61114. }
  61115. var url = rootUrl + sceneFilename;
  61116. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  61117. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  61118. } : undefined, database, useArrayBuffer, function (request, exception) {
  61119. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  61120. });
  61121. };
  61122. if (directLoad) {
  61123. dataCallback(directLoad);
  61124. return plugin;
  61125. }
  61126. if (rootUrl.indexOf("file:") === -1) {
  61127. if (scene.getEngine().enableOfflineSupport) {
  61128. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  61129. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  61130. }
  61131. else {
  61132. manifestChecked();
  61133. }
  61134. }
  61135. else {
  61136. var fileOrString = sceneFilename;
  61137. if (fileOrString.name) {
  61138. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  61139. }
  61140. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  61141. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  61142. }
  61143. else {
  61144. onError("Unable to find file named " + sceneFilename);
  61145. }
  61146. }
  61147. return plugin;
  61148. };
  61149. // Public functions
  61150. SceneLoader.GetPluginForExtension = function (extension) {
  61151. return SceneLoader._getPluginForExtension(extension).plugin;
  61152. };
  61153. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  61154. return !!SceneLoader._registeredPlugins[extension];
  61155. };
  61156. SceneLoader.RegisterPlugin = function (plugin) {
  61157. if (typeof plugin.extensions === "string") {
  61158. var extension = plugin.extensions;
  61159. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  61160. plugin: plugin,
  61161. isBinary: false
  61162. };
  61163. }
  61164. else {
  61165. var extensions = plugin.extensions;
  61166. Object.keys(extensions).forEach(function (extension) {
  61167. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  61168. plugin: plugin,
  61169. isBinary: extensions[extension].isBinary
  61170. };
  61171. });
  61172. }
  61173. };
  61174. /**
  61175. * Import meshes into a scene
  61176. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  61177. * @param rootUrl a string that defines the root url for scene and resources
  61178. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61179. * @param scene the instance of BABYLON.Scene to append to
  61180. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  61181. * @param onProgress a callback with a progress event for each file being loaded
  61182. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61183. * @param pluginExtension the extension used to determine the plugin
  61184. * @returns The loaded plugin
  61185. */
  61186. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61187. if (onSuccess === void 0) { onSuccess = null; }
  61188. if (onProgress === void 0) { onProgress = null; }
  61189. if (onError === void 0) { onError = null; }
  61190. if (pluginExtension === void 0) { pluginExtension = null; }
  61191. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61192. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61193. return null;
  61194. }
  61195. var loadingToken = {};
  61196. scene._addPendingData(loadingToken);
  61197. var disposeHandler = function () {
  61198. scene._removePendingData(loadingToken);
  61199. };
  61200. var errorHandler = function (message, exception) {
  61201. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  61202. if (onError) {
  61203. onError(scene, errorMessage, exception);
  61204. }
  61205. else {
  61206. BABYLON.Tools.Error(errorMessage);
  61207. // should the exception be thrown?
  61208. }
  61209. disposeHandler();
  61210. };
  61211. var progressHandler = onProgress ? function (event) {
  61212. try {
  61213. onProgress(event);
  61214. }
  61215. catch (e) {
  61216. errorHandler("Error in onProgress callback", e);
  61217. }
  61218. } : undefined;
  61219. var successHandler = function (meshes, particleSystems, skeletons) {
  61220. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  61221. if (onSuccess) {
  61222. try {
  61223. onSuccess(meshes, particleSystems, skeletons);
  61224. }
  61225. catch (e) {
  61226. errorHandler("Error in onSuccess callback", e);
  61227. }
  61228. }
  61229. scene._removePendingData(loadingToken);
  61230. };
  61231. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61232. if (plugin.rewriteRootURL) {
  61233. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  61234. }
  61235. if (sceneFilename === "") {
  61236. if (sceneFilename === "") {
  61237. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  61238. }
  61239. }
  61240. if (plugin.importMesh) {
  61241. var syncedPlugin = plugin;
  61242. var meshes = new Array();
  61243. var particleSystems = new Array();
  61244. var skeletons = new Array();
  61245. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  61246. return;
  61247. }
  61248. scene.loadingPluginName = plugin.name;
  61249. successHandler(meshes, particleSystems, skeletons);
  61250. }
  61251. else {
  61252. var asyncedPlugin = plugin;
  61253. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  61254. scene.loadingPluginName = plugin.name;
  61255. successHandler(result.meshes, result.particleSystems, result.skeletons);
  61256. }).catch(function (error) {
  61257. errorHandler(error.message, error);
  61258. });
  61259. }
  61260. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61261. };
  61262. /**
  61263. * Import meshes into a scene
  61264. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  61265. * @param rootUrl a string that defines the root url for scene and resources
  61266. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61267. * @param scene the instance of BABYLON.Scene to append to
  61268. * @param onProgress a callback with a progress event for each file being loaded
  61269. * @param pluginExtension the extension used to determine the plugin
  61270. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  61271. */
  61272. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61273. if (onProgress === void 0) { onProgress = null; }
  61274. if (pluginExtension === void 0) { pluginExtension = null; }
  61275. return new Promise(function (resolve, reject) {
  61276. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  61277. resolve({
  61278. meshes: meshes,
  61279. particleSystems: particleSystems,
  61280. skeletons: skeletons
  61281. });
  61282. }, onProgress, function (scene, message, exception) {
  61283. reject(exception || new Error(message));
  61284. });
  61285. });
  61286. };
  61287. /**
  61288. * Load a scene
  61289. * @param rootUrl a string that defines the root url for scene and resources
  61290. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61291. * @param engine is the instance of BABYLON.Engine to use to create the scene
  61292. * @param onSuccess a callback with the scene when import succeeds
  61293. * @param onProgress a callback with a progress event for each file being loaded
  61294. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61295. * @param pluginExtension the extension used to determine the plugin
  61296. * @returns The loaded plugin
  61297. */
  61298. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  61299. if (onSuccess === void 0) { onSuccess = null; }
  61300. if (onProgress === void 0) { onProgress = null; }
  61301. if (onError === void 0) { onError = null; }
  61302. if (pluginExtension === void 0) { pluginExtension = null; }
  61303. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  61304. };
  61305. /**
  61306. * Load a scene
  61307. * @param rootUrl a string that defines the root url for scene and resources
  61308. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61309. * @param engine is the instance of BABYLON.Engine to use to create the scene
  61310. * @param onProgress a callback with a progress event for each file being loaded
  61311. * @param pluginExtension the extension used to determine the plugin
  61312. * @returns The loaded scene
  61313. */
  61314. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  61315. if (onProgress === void 0) { onProgress = null; }
  61316. if (pluginExtension === void 0) { pluginExtension = null; }
  61317. return new Promise(function (resolve, reject) {
  61318. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  61319. resolve(scene);
  61320. }, onProgress, function (scene, message, exception) {
  61321. reject(exception || new Error(message));
  61322. }, pluginExtension);
  61323. });
  61324. };
  61325. /**
  61326. * Append a scene
  61327. * @param rootUrl a string that defines the root url for scene and resources
  61328. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61329. * @param scene is the instance of BABYLON.Scene to append to
  61330. * @param onSuccess a callback with the scene when import succeeds
  61331. * @param onProgress a callback with a progress event for each file being loaded
  61332. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61333. * @param pluginExtension the extension used to determine the plugin
  61334. * @returns The loaded plugin
  61335. */
  61336. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61337. if (onSuccess === void 0) { onSuccess = null; }
  61338. if (onProgress === void 0) { onProgress = null; }
  61339. if (onError === void 0) { onError = null; }
  61340. if (pluginExtension === void 0) { pluginExtension = null; }
  61341. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61342. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61343. return null;
  61344. }
  61345. if (SceneLoader.ShowLoadingScreen) {
  61346. scene.getEngine().displayLoadingUI();
  61347. }
  61348. var loadingToken = {};
  61349. scene._addPendingData(loadingToken);
  61350. var disposeHandler = function () {
  61351. scene._removePendingData(loadingToken);
  61352. scene.getEngine().hideLoadingUI();
  61353. };
  61354. var errorHandler = function (message, exception) {
  61355. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  61356. if (onError) {
  61357. onError(scene, errorMessage, exception);
  61358. }
  61359. else {
  61360. BABYLON.Tools.Error(errorMessage);
  61361. // should the exception be thrown?
  61362. }
  61363. disposeHandler();
  61364. };
  61365. var progressHandler = onProgress ? function (event) {
  61366. try {
  61367. onProgress(event);
  61368. }
  61369. catch (e) {
  61370. errorHandler("Error in onProgress callback", e);
  61371. }
  61372. } : undefined;
  61373. var successHandler = function () {
  61374. if (onSuccess) {
  61375. try {
  61376. onSuccess(scene);
  61377. }
  61378. catch (e) {
  61379. errorHandler("Error in onSuccess callback", e);
  61380. }
  61381. }
  61382. scene._removePendingData(loadingToken);
  61383. };
  61384. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61385. if (sceneFilename === "") {
  61386. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  61387. }
  61388. if (plugin.load) {
  61389. var syncedPlugin = plugin;
  61390. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  61391. return;
  61392. }
  61393. scene.loadingPluginName = plugin.name;
  61394. successHandler();
  61395. }
  61396. else {
  61397. var asyncedPlugin = plugin;
  61398. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  61399. scene.loadingPluginName = plugin.name;
  61400. successHandler();
  61401. }).catch(function (error) {
  61402. errorHandler(error.message, error);
  61403. });
  61404. }
  61405. if (SceneLoader.ShowLoadingScreen) {
  61406. scene.executeWhenReady(function () {
  61407. scene.getEngine().hideLoadingUI();
  61408. });
  61409. }
  61410. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61411. };
  61412. /**
  61413. * Append a scene
  61414. * @param rootUrl a string that defines the root url for scene and resources
  61415. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61416. * @param scene is the instance of BABYLON.Scene to append to
  61417. * @param onProgress a callback with a progress event for each file being loaded
  61418. * @param pluginExtension the extension used to determine the plugin
  61419. * @returns The given scene
  61420. */
  61421. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61422. if (onProgress === void 0) { onProgress = null; }
  61423. if (pluginExtension === void 0) { pluginExtension = null; }
  61424. return new Promise(function (resolve, reject) {
  61425. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  61426. resolve(scene);
  61427. }, onProgress, function (scene, message, exception) {
  61428. reject(exception || new Error(message));
  61429. }, pluginExtension);
  61430. });
  61431. };
  61432. /**
  61433. * Load a scene into an asset container
  61434. * @param rootUrl a string that defines the root url for scene and resources
  61435. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61436. * @param scene is the instance of BABYLON.Scene to append to
  61437. * @param onSuccess a callback with the scene when import succeeds
  61438. * @param onProgress a callback with a progress event for each file being loaded
  61439. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61440. * @param pluginExtension the extension used to determine the plugin
  61441. * @returns The loaded plugin
  61442. */
  61443. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61444. if (onSuccess === void 0) { onSuccess = null; }
  61445. if (onProgress === void 0) { onProgress = null; }
  61446. if (onError === void 0) { onError = null; }
  61447. if (pluginExtension === void 0) { pluginExtension = null; }
  61448. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61449. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61450. return null;
  61451. }
  61452. var loadingToken = {};
  61453. scene._addPendingData(loadingToken);
  61454. var disposeHandler = function () {
  61455. scene._removePendingData(loadingToken);
  61456. };
  61457. var errorHandler = function (message, exception) {
  61458. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  61459. if (onError) {
  61460. onError(scene, errorMessage, exception);
  61461. }
  61462. else {
  61463. BABYLON.Tools.Error(errorMessage);
  61464. // should the exception be thrown?
  61465. }
  61466. disposeHandler();
  61467. };
  61468. var progressHandler = onProgress ? function (event) {
  61469. try {
  61470. onProgress(event);
  61471. }
  61472. catch (e) {
  61473. errorHandler("Error in onProgress callback", e);
  61474. }
  61475. } : undefined;
  61476. var successHandler = function (assets) {
  61477. if (onSuccess) {
  61478. try {
  61479. onSuccess(assets);
  61480. }
  61481. catch (e) {
  61482. errorHandler("Error in onSuccess callback", e);
  61483. }
  61484. }
  61485. scene._removePendingData(loadingToken);
  61486. };
  61487. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61488. if (plugin.loadAssetContainer) {
  61489. var syncedPlugin = plugin;
  61490. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  61491. if (!assetContainer) {
  61492. return;
  61493. }
  61494. scene.loadingPluginName = plugin.name;
  61495. successHandler(assetContainer);
  61496. }
  61497. else if (plugin.loadAssetContainerAsync) {
  61498. var asyncedPlugin = plugin;
  61499. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  61500. scene.loadingPluginName = plugin.name;
  61501. successHandler(assetContainer);
  61502. }).catch(function (error) {
  61503. errorHandler(error.message, error);
  61504. });
  61505. }
  61506. else {
  61507. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  61508. }
  61509. if (SceneLoader.ShowLoadingScreen) {
  61510. scene.executeWhenReady(function () {
  61511. scene.getEngine().hideLoadingUI();
  61512. });
  61513. }
  61514. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61515. };
  61516. /**
  61517. * Load a scene into an asset container
  61518. * @param rootUrl a string that defines the root url for scene and resources
  61519. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61520. * @param scene is the instance of BABYLON.Scene to append to
  61521. * @param onProgress a callback with a progress event for each file being loaded
  61522. * @param pluginExtension the extension used to determine the plugin
  61523. * @returns The loaded asset container
  61524. */
  61525. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61526. if (onProgress === void 0) { onProgress = null; }
  61527. if (pluginExtension === void 0) { pluginExtension = null; }
  61528. return new Promise(function (resolve, reject) {
  61529. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  61530. resolve(assetContainer);
  61531. }, onProgress, function (scene, message, exception) {
  61532. reject(exception || new Error(message));
  61533. }, pluginExtension);
  61534. });
  61535. };
  61536. // Flags
  61537. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  61538. SceneLoader._ShowLoadingScreen = true;
  61539. SceneLoader._CleanBoneMatrixWeights = false;
  61540. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  61541. // Members
  61542. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  61543. SceneLoader._registeredPlugins = {};
  61544. return SceneLoader;
  61545. }());
  61546. BABYLON.SceneLoader = SceneLoader;
  61547. ;
  61548. })(BABYLON || (BABYLON = {}));
  61549. //# sourceMappingURL=babylon.sceneLoader.js.map
  61550. var BABYLON;
  61551. (function (BABYLON) {
  61552. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  61553. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  61554. var parsedMaterial = parsedData.materials[index];
  61555. if (parsedMaterial.id === id) {
  61556. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  61557. }
  61558. }
  61559. return null;
  61560. };
  61561. var isDescendantOf = function (mesh, names, hierarchyIds) {
  61562. for (var i in names) {
  61563. if (mesh.name === names[i]) {
  61564. hierarchyIds.push(mesh.id);
  61565. return true;
  61566. }
  61567. }
  61568. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  61569. hierarchyIds.push(mesh.id);
  61570. return true;
  61571. }
  61572. return false;
  61573. };
  61574. var logOperation = function (operation, producer) {
  61575. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  61576. };
  61577. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  61578. if (addToScene === void 0) { addToScene = false; }
  61579. var container = new BABYLON.AssetContainer(scene);
  61580. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61581. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61582. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61583. // and avoid problems with multiple concurrent .babylon loads.
  61584. var log = "importScene has failed JSON parse";
  61585. try {
  61586. var parsedData = JSON.parse(data);
  61587. log = "";
  61588. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  61589. var index;
  61590. var cache;
  61591. // Lights
  61592. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  61593. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  61594. var parsedLight = parsedData.lights[index];
  61595. var light = BABYLON.Light.Parse(parsedLight, scene);
  61596. if (light) {
  61597. container.lights.push(light);
  61598. log += (index === 0 ? "\n\tLights:" : "");
  61599. log += "\n\t\t" + light.toString(fullDetails);
  61600. }
  61601. }
  61602. }
  61603. // Animations
  61604. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  61605. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  61606. var parsedAnimation = parsedData.animations[index];
  61607. var animation = BABYLON.Animation.Parse(parsedAnimation);
  61608. scene.animations.push(animation);
  61609. container.animations.push(animation);
  61610. log += (index === 0 ? "\n\tAnimations:" : "");
  61611. log += "\n\t\t" + animation.toString(fullDetails);
  61612. }
  61613. }
  61614. // Materials
  61615. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  61616. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  61617. var parsedMaterial = parsedData.materials[index];
  61618. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  61619. container.materials.push(mat);
  61620. log += (index === 0 ? "\n\tMaterials:" : "");
  61621. log += "\n\t\t" + mat.toString(fullDetails);
  61622. }
  61623. }
  61624. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  61625. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  61626. var parsedMultiMaterial = parsedData.multiMaterials[index];
  61627. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  61628. container.multiMaterials.push(mmat);
  61629. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  61630. log += "\n\t\t" + mmat.toString(fullDetails);
  61631. }
  61632. }
  61633. // Morph targets
  61634. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  61635. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  61636. var managerData = _a[_i];
  61637. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  61638. }
  61639. }
  61640. // Skeletons
  61641. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  61642. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  61643. var parsedSkeleton = parsedData.skeletons[index];
  61644. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  61645. container.skeletons.push(skeleton);
  61646. log += (index === 0 ? "\n\tSkeletons:" : "");
  61647. log += "\n\t\t" + skeleton.toString(fullDetails);
  61648. }
  61649. }
  61650. // Geometries
  61651. var geometries = parsedData.geometries;
  61652. if (geometries !== undefined && geometries !== null) {
  61653. var addedGeometry = new Array();
  61654. // Boxes
  61655. var boxes = geometries.boxes;
  61656. if (boxes !== undefined && boxes !== null) {
  61657. for (index = 0, cache = boxes.length; index < cache; index++) {
  61658. var parsedBox = boxes[index];
  61659. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  61660. }
  61661. }
  61662. // Spheres
  61663. var spheres = geometries.spheres;
  61664. if (spheres !== undefined && spheres !== null) {
  61665. for (index = 0, cache = spheres.length; index < cache; index++) {
  61666. var parsedSphere = spheres[index];
  61667. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  61668. }
  61669. }
  61670. // Cylinders
  61671. var cylinders = geometries.cylinders;
  61672. if (cylinders !== undefined && cylinders !== null) {
  61673. for (index = 0, cache = cylinders.length; index < cache; index++) {
  61674. var parsedCylinder = cylinders[index];
  61675. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  61676. }
  61677. }
  61678. // Toruses
  61679. var toruses = geometries.toruses;
  61680. if (toruses !== undefined && toruses !== null) {
  61681. for (index = 0, cache = toruses.length; index < cache; index++) {
  61682. var parsedTorus = toruses[index];
  61683. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  61684. }
  61685. }
  61686. // Grounds
  61687. var grounds = geometries.grounds;
  61688. if (grounds !== undefined && grounds !== null) {
  61689. for (index = 0, cache = grounds.length; index < cache; index++) {
  61690. var parsedGround = grounds[index];
  61691. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  61692. }
  61693. }
  61694. // Planes
  61695. var planes = geometries.planes;
  61696. if (planes !== undefined && planes !== null) {
  61697. for (index = 0, cache = planes.length; index < cache; index++) {
  61698. var parsedPlane = planes[index];
  61699. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  61700. }
  61701. }
  61702. // TorusKnots
  61703. var torusKnots = geometries.torusKnots;
  61704. if (torusKnots !== undefined && torusKnots !== null) {
  61705. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  61706. var parsedTorusKnot = torusKnots[index];
  61707. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  61708. }
  61709. }
  61710. // VertexData
  61711. var vertexData = geometries.vertexData;
  61712. if (vertexData !== undefined && vertexData !== null) {
  61713. for (index = 0, cache = vertexData.length; index < cache; index++) {
  61714. var parsedVertexData = vertexData[index];
  61715. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  61716. }
  61717. }
  61718. addedGeometry.forEach(function (g) {
  61719. if (g) {
  61720. container.geometries.push(g);
  61721. }
  61722. });
  61723. }
  61724. // Transform nodes
  61725. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  61726. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  61727. var parsedTransformNode = parsedData.transformNodes[index];
  61728. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  61729. container.transformNodes.push(node);
  61730. }
  61731. }
  61732. // Meshes
  61733. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  61734. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  61735. var parsedMesh = parsedData.meshes[index];
  61736. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  61737. container.meshes.push(mesh);
  61738. log += (index === 0 ? "\n\tMeshes:" : "");
  61739. log += "\n\t\t" + mesh.toString(fullDetails);
  61740. }
  61741. }
  61742. // Cameras
  61743. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  61744. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  61745. var parsedCamera = parsedData.cameras[index];
  61746. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  61747. container.cameras.push(camera);
  61748. log += (index === 0 ? "\n\tCameras:" : "");
  61749. log += "\n\t\t" + camera.toString(fullDetails);
  61750. }
  61751. }
  61752. // Browsing all the graph to connect the dots
  61753. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  61754. var camera = scene.cameras[index];
  61755. if (camera._waitingParentId) {
  61756. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  61757. camera._waitingParentId = null;
  61758. }
  61759. }
  61760. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  61761. var light_1 = scene.lights[index];
  61762. if (light_1 && light_1._waitingParentId) {
  61763. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  61764. light_1._waitingParentId = null;
  61765. }
  61766. }
  61767. // Sounds
  61768. // TODO: add sound
  61769. var loadedSounds = [];
  61770. var loadedSound;
  61771. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  61772. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  61773. var parsedSound = parsedData.sounds[index];
  61774. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61775. if (!parsedSound.url)
  61776. parsedSound.url = parsedSound.name;
  61777. if (!loadedSounds[parsedSound.url]) {
  61778. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  61779. loadedSounds[parsedSound.url] = loadedSound;
  61780. container.sounds.push(loadedSound);
  61781. }
  61782. else {
  61783. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  61784. }
  61785. }
  61786. else {
  61787. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  61788. }
  61789. }
  61790. }
  61791. loadedSounds = [];
  61792. // Connect parents & children and parse actions
  61793. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  61794. var transformNode = scene.transformNodes[index];
  61795. if (transformNode._waitingParentId) {
  61796. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  61797. transformNode._waitingParentId = null;
  61798. }
  61799. }
  61800. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61801. var mesh = scene.meshes[index];
  61802. if (mesh._waitingParentId) {
  61803. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  61804. mesh._waitingParentId = null;
  61805. }
  61806. if (mesh._waitingActions) {
  61807. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  61808. mesh._waitingActions = null;
  61809. }
  61810. }
  61811. // freeze world matrix application
  61812. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61813. var currentMesh = scene.meshes[index];
  61814. if (currentMesh._waitingFreezeWorldMatrix) {
  61815. currentMesh.freezeWorldMatrix();
  61816. currentMesh._waitingFreezeWorldMatrix = null;
  61817. }
  61818. else {
  61819. currentMesh.computeWorldMatrix(true);
  61820. }
  61821. }
  61822. // Particles Systems
  61823. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  61824. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  61825. var parsedParticleSystem = parsedData.particleSystems[index];
  61826. if (parsedParticleSystem.activeParticleCount) {
  61827. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61828. container.particleSystems.push(ps);
  61829. }
  61830. else {
  61831. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61832. container.particleSystems.push(ps);
  61833. }
  61834. }
  61835. }
  61836. // Lens flares
  61837. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  61838. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  61839. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  61840. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  61841. container.lensFlareSystems.push(lf);
  61842. }
  61843. }
  61844. // Shadows
  61845. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  61846. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  61847. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  61848. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  61849. container.shadowGenerators.push(sg);
  61850. }
  61851. }
  61852. // Lights exclusions / inclusions
  61853. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  61854. var light_2 = scene.lights[index];
  61855. // Excluded check
  61856. if (light_2._excludedMeshesIds.length > 0) {
  61857. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  61858. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  61859. if (excludedMesh) {
  61860. light_2.excludedMeshes.push(excludedMesh);
  61861. }
  61862. }
  61863. light_2._excludedMeshesIds = [];
  61864. }
  61865. // Included check
  61866. if (light_2._includedOnlyMeshesIds.length > 0) {
  61867. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  61868. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  61869. if (includedOnlyMesh) {
  61870. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  61871. }
  61872. }
  61873. light_2._includedOnlyMeshesIds = [];
  61874. }
  61875. }
  61876. // Actions (scene)
  61877. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  61878. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  61879. }
  61880. if (!addToScene) {
  61881. container.removeAllFromScene();
  61882. }
  61883. }
  61884. catch (err) {
  61885. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  61886. if (onError) {
  61887. onError(msg, err);
  61888. }
  61889. else {
  61890. BABYLON.Tools.Log(msg);
  61891. throw err;
  61892. }
  61893. }
  61894. finally {
  61895. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61896. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61897. }
  61898. }
  61899. return container;
  61900. };
  61901. BABYLON.SceneLoader.RegisterPlugin({
  61902. name: "babylon.js",
  61903. extensions: ".babylon",
  61904. canDirectLoad: function (data) {
  61905. if (data.indexOf("babylon") !== -1) {
  61906. return true;
  61907. }
  61908. return false;
  61909. },
  61910. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  61911. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61912. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61913. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61914. // and avoid problems with multiple concurrent .babylon loads.
  61915. var log = "importMesh has failed JSON parse";
  61916. try {
  61917. var parsedData = JSON.parse(data);
  61918. log = "";
  61919. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  61920. if (!meshesNames) {
  61921. meshesNames = null;
  61922. }
  61923. else if (!Array.isArray(meshesNames)) {
  61924. meshesNames = [meshesNames];
  61925. }
  61926. var hierarchyIds = new Array();
  61927. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  61928. var loadedSkeletonsIds = [];
  61929. var loadedMaterialsIds = [];
  61930. var index;
  61931. var cache;
  61932. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  61933. var parsedMesh = parsedData.meshes[index];
  61934. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  61935. if (meshesNames !== null) {
  61936. // Remove found mesh name from list.
  61937. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  61938. }
  61939. //Geometry?
  61940. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  61941. //does the file contain geometries?
  61942. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  61943. //find the correct geometry and add it to the scene
  61944. var found = false;
  61945. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  61946. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  61947. return;
  61948. }
  61949. else {
  61950. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  61951. if (parsedGeometryData.id === parsedMesh.geometryId) {
  61952. switch (geometryType) {
  61953. case "boxes":
  61954. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  61955. break;
  61956. case "spheres":
  61957. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  61958. break;
  61959. case "cylinders":
  61960. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  61961. break;
  61962. case "toruses":
  61963. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  61964. break;
  61965. case "grounds":
  61966. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  61967. break;
  61968. case "planes":
  61969. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  61970. break;
  61971. case "torusKnots":
  61972. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  61973. break;
  61974. case "vertexData":
  61975. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  61976. break;
  61977. }
  61978. found = true;
  61979. }
  61980. });
  61981. }
  61982. });
  61983. if (found === false) {
  61984. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  61985. }
  61986. }
  61987. }
  61988. // Material ?
  61989. if (parsedMesh.materialId) {
  61990. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  61991. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  61992. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  61993. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  61994. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  61995. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  61996. var subMatId = parsedMultiMaterial.materials[matIndex];
  61997. loadedMaterialsIds.push(subMatId);
  61998. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  61999. if (mat) {
  62000. log += "\n\tMaterial " + mat.toString(fullDetails);
  62001. }
  62002. }
  62003. loadedMaterialsIds.push(parsedMultiMaterial.id);
  62004. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  62005. if (mmat) {
  62006. materialFound = true;
  62007. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  62008. }
  62009. break;
  62010. }
  62011. }
  62012. }
  62013. if (materialFound === false) {
  62014. loadedMaterialsIds.push(parsedMesh.materialId);
  62015. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  62016. if (!mat) {
  62017. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  62018. }
  62019. else {
  62020. log += "\n\tMaterial " + mat.toString(fullDetails);
  62021. }
  62022. }
  62023. }
  62024. // Skeleton ?
  62025. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  62026. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  62027. if (skeletonAlreadyLoaded === false) {
  62028. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  62029. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  62030. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  62031. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  62032. skeletons.push(skeleton);
  62033. loadedSkeletonsIds.push(parsedSkeleton.id);
  62034. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  62035. }
  62036. }
  62037. }
  62038. }
  62039. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  62040. meshes.push(mesh);
  62041. log += "\n\tMesh " + mesh.toString(fullDetails);
  62042. }
  62043. }
  62044. // Connecting parents
  62045. var currentMesh;
  62046. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62047. currentMesh = scene.meshes[index];
  62048. if (currentMesh._waitingParentId) {
  62049. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  62050. currentMesh._waitingParentId = null;
  62051. }
  62052. }
  62053. // freeze and compute world matrix application
  62054. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62055. currentMesh = scene.meshes[index];
  62056. if (currentMesh._waitingFreezeWorldMatrix) {
  62057. currentMesh.freezeWorldMatrix();
  62058. currentMesh._waitingFreezeWorldMatrix = null;
  62059. }
  62060. else {
  62061. currentMesh.computeWorldMatrix(true);
  62062. }
  62063. }
  62064. }
  62065. // Particles
  62066. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  62067. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  62068. var parsedParticleSystem = parsedData.particleSystems[index];
  62069. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  62070. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  62071. }
  62072. }
  62073. }
  62074. return true;
  62075. }
  62076. catch (err) {
  62077. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  62078. if (onError) {
  62079. onError(msg, err);
  62080. }
  62081. else {
  62082. BABYLON.Tools.Log(msg);
  62083. throw err;
  62084. }
  62085. }
  62086. finally {
  62087. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62088. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62089. }
  62090. }
  62091. return false;
  62092. },
  62093. load: function (scene, data, rootUrl, onError) {
  62094. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62095. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62096. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62097. // and avoid problems with multiple concurrent .babylon loads.
  62098. var log = "importScene has failed JSON parse";
  62099. try {
  62100. var parsedData = JSON.parse(data);
  62101. log = "";
  62102. // Scene
  62103. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  62104. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  62105. }
  62106. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  62107. scene.autoClear = parsedData.autoClear;
  62108. }
  62109. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  62110. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  62111. }
  62112. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  62113. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  62114. }
  62115. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  62116. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  62117. }
  62118. // Fog
  62119. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  62120. scene.fogMode = parsedData.fogMode;
  62121. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  62122. scene.fogStart = parsedData.fogStart;
  62123. scene.fogEnd = parsedData.fogEnd;
  62124. scene.fogDensity = parsedData.fogDensity;
  62125. log += "\tFog mode for scene: ";
  62126. switch (scene.fogMode) {
  62127. // getters not compiling, so using hardcoded
  62128. case 1:
  62129. log += "exp\n";
  62130. break;
  62131. case 2:
  62132. log += "exp2\n";
  62133. break;
  62134. case 3:
  62135. log += "linear\n";
  62136. break;
  62137. }
  62138. }
  62139. //Physics
  62140. if (parsedData.physicsEnabled) {
  62141. var physicsPlugin;
  62142. if (parsedData.physicsEngine === "cannon") {
  62143. physicsPlugin = new BABYLON.CannonJSPlugin();
  62144. }
  62145. else if (parsedData.physicsEngine === "oimo") {
  62146. physicsPlugin = new BABYLON.OimoJSPlugin();
  62147. }
  62148. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  62149. //else - default engine, which is currently oimo
  62150. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  62151. scene.enablePhysics(physicsGravity, physicsPlugin);
  62152. }
  62153. // Metadata
  62154. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  62155. scene.metadata = parsedData.metadata;
  62156. }
  62157. //collisions, if defined. otherwise, default is true
  62158. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  62159. scene.collisionsEnabled = parsedData.collisionsEnabled;
  62160. }
  62161. scene.workerCollisions = !!parsedData.workerCollisions;
  62162. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  62163. if (!container) {
  62164. return false;
  62165. }
  62166. if (parsedData.autoAnimate) {
  62167. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  62168. }
  62169. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  62170. scene.setActiveCameraByID(parsedData.activeCameraID);
  62171. }
  62172. // Environment texture
  62173. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  62174. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  62175. if (parsedData.createDefaultSkybox === true) {
  62176. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  62177. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  62178. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  62179. }
  62180. }
  62181. // Finish
  62182. return true;
  62183. }
  62184. catch (err) {
  62185. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  62186. if (onError) {
  62187. onError(msg, err);
  62188. }
  62189. else {
  62190. BABYLON.Tools.Log(msg);
  62191. throw err;
  62192. }
  62193. }
  62194. finally {
  62195. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62196. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62197. }
  62198. }
  62199. return false;
  62200. },
  62201. loadAssetContainer: function (scene, data, rootUrl, onError) {
  62202. var container = loadAssetContainer(scene, data, rootUrl, onError);
  62203. return container;
  62204. }
  62205. });
  62206. })(BABYLON || (BABYLON = {}));
  62207. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  62208. var BABYLON;
  62209. (function (BABYLON) {
  62210. var FilesInput = /** @class */ (function () {
  62211. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  62212. this.onProcessFileCallback = function () { return true; };
  62213. this._engine = engine;
  62214. this._currentScene = scene;
  62215. this._sceneLoadedCallback = sceneLoadedCallback;
  62216. this._progressCallback = progressCallback;
  62217. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  62218. this._textureLoadingCallback = textureLoadingCallback;
  62219. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  62220. this._onReloadCallback = onReloadCallback;
  62221. this._errorCallback = errorCallback;
  62222. }
  62223. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  62224. var _this = this;
  62225. if (elementToMonitor) {
  62226. this._elementToMonitor = elementToMonitor;
  62227. this._dragEnterHandler = function (e) { _this.drag(e); };
  62228. this._dragOverHandler = function (e) { _this.drag(e); };
  62229. this._dropHandler = function (e) { _this.drop(e); };
  62230. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  62231. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  62232. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  62233. }
  62234. };
  62235. FilesInput.prototype.dispose = function () {
  62236. if (!this._elementToMonitor) {
  62237. return;
  62238. }
  62239. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  62240. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  62241. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  62242. };
  62243. FilesInput.prototype.renderFunction = function () {
  62244. if (this._additionalRenderLoopLogicCallback) {
  62245. this._additionalRenderLoopLogicCallback();
  62246. }
  62247. if (this._currentScene) {
  62248. if (this._textureLoadingCallback) {
  62249. var remaining = this._currentScene.getWaitingItemsCount();
  62250. if (remaining > 0) {
  62251. this._textureLoadingCallback(remaining);
  62252. }
  62253. }
  62254. this._currentScene.render();
  62255. }
  62256. };
  62257. FilesInput.prototype.drag = function (e) {
  62258. e.stopPropagation();
  62259. e.preventDefault();
  62260. };
  62261. FilesInput.prototype.drop = function (eventDrop) {
  62262. eventDrop.stopPropagation();
  62263. eventDrop.preventDefault();
  62264. this.loadFiles(eventDrop);
  62265. };
  62266. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  62267. var _this = this;
  62268. var reader = folder.createReader();
  62269. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  62270. reader.readEntries(function (entries) {
  62271. remaining.count += entries.length;
  62272. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  62273. var entry = entries_1[_i];
  62274. if (entry.isFile) {
  62275. entry.file(function (file) {
  62276. file.correctName = relativePath + file.name;
  62277. files.push(file);
  62278. if (--remaining.count === 0) {
  62279. callback();
  62280. }
  62281. });
  62282. }
  62283. else if (entry.isDirectory) {
  62284. _this._traverseFolder(entry, files, remaining, callback);
  62285. }
  62286. }
  62287. if (--remaining.count) {
  62288. callback();
  62289. }
  62290. });
  62291. };
  62292. FilesInput.prototype._processFiles = function (files) {
  62293. for (var i = 0; i < files.length; i++) {
  62294. var name = files[i].correctName.toLowerCase();
  62295. var extension = name.split('.').pop();
  62296. if (!this.onProcessFileCallback(files[i], name, extension)) {
  62297. continue;
  62298. }
  62299. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  62300. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  62301. this._sceneFileToLoad = files[i];
  62302. }
  62303. else {
  62304. FilesInput.FilesToLoad[name] = files[i];
  62305. }
  62306. }
  62307. };
  62308. FilesInput.prototype.loadFiles = function (event) {
  62309. var _this = this;
  62310. if (this._startingProcessingFilesCallback)
  62311. this._startingProcessingFilesCallback();
  62312. // Handling data transfer via drag'n'drop
  62313. if (event && event.dataTransfer && event.dataTransfer.files) {
  62314. this._filesToLoad = event.dataTransfer.files;
  62315. }
  62316. // Handling files from input files
  62317. if (event && event.target && event.target.files) {
  62318. this._filesToLoad = event.target.files;
  62319. }
  62320. if (this._filesToLoad && this._filesToLoad.length > 0) {
  62321. var files_1 = new Array();
  62322. var folders = [];
  62323. var items = event.dataTransfer ? event.dataTransfer.items : null;
  62324. for (var i = 0; i < this._filesToLoad.length; i++) {
  62325. var fileToLoad = this._filesToLoad[i];
  62326. var name_1 = fileToLoad.name.toLowerCase();
  62327. var entry = void 0;
  62328. fileToLoad.correctName = name_1;
  62329. if (items) {
  62330. var item = items[i];
  62331. if (item.getAsEntry) {
  62332. entry = item.getAsEntry();
  62333. }
  62334. else if (item.webkitGetAsEntry) {
  62335. entry = item.webkitGetAsEntry();
  62336. }
  62337. }
  62338. if (!entry) {
  62339. files_1.push(fileToLoad);
  62340. }
  62341. else {
  62342. if (entry.isDirectory) {
  62343. folders.push(entry);
  62344. }
  62345. else {
  62346. files_1.push(fileToLoad);
  62347. }
  62348. }
  62349. }
  62350. if (folders.length === 0) {
  62351. this._processFiles(files_1);
  62352. this._processReload();
  62353. }
  62354. else {
  62355. var remaining = { count: folders.length };
  62356. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  62357. var folder = folders_1[_i];
  62358. this._traverseFolder(folder, files_1, remaining, function () {
  62359. _this._processFiles(files_1);
  62360. if (remaining.count === 0) {
  62361. _this._processReload();
  62362. }
  62363. });
  62364. }
  62365. }
  62366. }
  62367. };
  62368. FilesInput.prototype._processReload = function () {
  62369. if (this._onReloadCallback) {
  62370. this._onReloadCallback(this._sceneFileToLoad);
  62371. }
  62372. else {
  62373. this.reload();
  62374. }
  62375. };
  62376. FilesInput.prototype.reload = function () {
  62377. var _this = this;
  62378. // If a scene file has been provided
  62379. if (this._sceneFileToLoad) {
  62380. if (this._currentScene) {
  62381. if (BABYLON.Tools.errorsCount > 0) {
  62382. BABYLON.Tools.ClearLogCache();
  62383. }
  62384. this._engine.stopRenderLoop();
  62385. this._currentScene.dispose();
  62386. }
  62387. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  62388. if (_this._progressCallback) {
  62389. _this._progressCallback(progress);
  62390. }
  62391. }).then(function (scene) {
  62392. _this._currentScene = scene;
  62393. if (_this._sceneLoadedCallback) {
  62394. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  62395. }
  62396. // Wait for textures and shaders to be ready
  62397. _this._currentScene.executeWhenReady(function () {
  62398. _this._engine.runRenderLoop(function () {
  62399. _this.renderFunction();
  62400. });
  62401. });
  62402. }).catch(function (error) {
  62403. if (_this._errorCallback) {
  62404. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  62405. }
  62406. });
  62407. }
  62408. else {
  62409. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  62410. }
  62411. };
  62412. FilesInput.FilesToLoad = {};
  62413. return FilesInput;
  62414. }());
  62415. BABYLON.FilesInput = FilesInput;
  62416. })(BABYLON || (BABYLON = {}));
  62417. //# sourceMappingURL=babylon.filesInput.js.map
  62418. var BABYLON;
  62419. (function (BABYLON) {
  62420. /**
  62421. * This class implement a typical dictionary using a string as key and the generic type T as value.
  62422. * The underlying implementation relies on an associative array to ensure the best performances.
  62423. * The value can be anything including 'null' but except 'undefined'
  62424. */
  62425. var StringDictionary = /** @class */ (function () {
  62426. function StringDictionary() {
  62427. this._count = 0;
  62428. this._data = {};
  62429. }
  62430. /**
  62431. * This will clear this dictionary and copy the content from the 'source' one.
  62432. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  62433. * @param source the dictionary to take the content from and copy to this dictionary
  62434. */
  62435. StringDictionary.prototype.copyFrom = function (source) {
  62436. var _this = this;
  62437. this.clear();
  62438. source.forEach(function (t, v) { return _this.add(t, v); });
  62439. };
  62440. /**
  62441. * Get a value based from its key
  62442. * @param key the given key to get the matching value from
  62443. * @return the value if found, otherwise undefined is returned
  62444. */
  62445. StringDictionary.prototype.get = function (key) {
  62446. var val = this._data[key];
  62447. if (val !== undefined) {
  62448. return val;
  62449. }
  62450. return undefined;
  62451. };
  62452. /**
  62453. * Get a value from its key or add it if it doesn't exist.
  62454. * This method will ensure you that a given key/data will be present in the dictionary.
  62455. * @param key the given key to get the matching value from
  62456. * @param factory the factory that will create the value if the key is not present in the dictionary.
  62457. * The factory will only be invoked if there's no data for the given key.
  62458. * @return the value corresponding to the key.
  62459. */
  62460. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  62461. var val = this.get(key);
  62462. if (val !== undefined) {
  62463. return val;
  62464. }
  62465. val = factory(key);
  62466. if (val) {
  62467. this.add(key, val);
  62468. }
  62469. return val;
  62470. };
  62471. /**
  62472. * Get a value from its key if present in the dictionary otherwise add it
  62473. * @param key the key to get the value from
  62474. * @param val if there's no such key/value pair in the dictionary add it with this value
  62475. * @return the value corresponding to the key
  62476. */
  62477. StringDictionary.prototype.getOrAdd = function (key, val) {
  62478. var curVal = this.get(key);
  62479. if (curVal !== undefined) {
  62480. return curVal;
  62481. }
  62482. this.add(key, val);
  62483. return val;
  62484. };
  62485. /**
  62486. * Check if there's a given key in the dictionary
  62487. * @param key the key to check for
  62488. * @return true if the key is present, false otherwise
  62489. */
  62490. StringDictionary.prototype.contains = function (key) {
  62491. return this._data[key] !== undefined;
  62492. };
  62493. /**
  62494. * Add a new key and its corresponding value
  62495. * @param key the key to add
  62496. * @param value the value corresponding to the key
  62497. * @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
  62498. */
  62499. StringDictionary.prototype.add = function (key, value) {
  62500. if (this._data[key] !== undefined) {
  62501. return false;
  62502. }
  62503. this._data[key] = value;
  62504. ++this._count;
  62505. return true;
  62506. };
  62507. StringDictionary.prototype.set = function (key, value) {
  62508. if (this._data[key] === undefined) {
  62509. return false;
  62510. }
  62511. this._data[key] = value;
  62512. return true;
  62513. };
  62514. /**
  62515. * Get the element of the given key and remove it from the dictionary
  62516. * @param key
  62517. */
  62518. StringDictionary.prototype.getAndRemove = function (key) {
  62519. var val = this.get(key);
  62520. if (val !== undefined) {
  62521. delete this._data[key];
  62522. --this._count;
  62523. return val;
  62524. }
  62525. return null;
  62526. };
  62527. /**
  62528. * Remove a key/value from the dictionary.
  62529. * @param key the key to remove
  62530. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  62531. */
  62532. StringDictionary.prototype.remove = function (key) {
  62533. if (this.contains(key)) {
  62534. delete this._data[key];
  62535. --this._count;
  62536. return true;
  62537. }
  62538. return false;
  62539. };
  62540. /**
  62541. * Clear the whole content of the dictionary
  62542. */
  62543. StringDictionary.prototype.clear = function () {
  62544. this._data = {};
  62545. this._count = 0;
  62546. };
  62547. Object.defineProperty(StringDictionary.prototype, "count", {
  62548. get: function () {
  62549. return this._count;
  62550. },
  62551. enumerable: true,
  62552. configurable: true
  62553. });
  62554. /**
  62555. * Execute a callback on each key/val of the dictionary.
  62556. * Note that you can remove any element in this dictionary in the callback implementation
  62557. * @param callback the callback to execute on a given key/value pair
  62558. */
  62559. StringDictionary.prototype.forEach = function (callback) {
  62560. for (var cur in this._data) {
  62561. var val = this._data[cur];
  62562. callback(cur, val);
  62563. }
  62564. };
  62565. /**
  62566. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  62567. * If the callback returns null or undefined the method will iterate to the next key/value pair
  62568. * Note that you can remove any element in this dictionary in the callback implementation
  62569. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  62570. */
  62571. StringDictionary.prototype.first = function (callback) {
  62572. for (var cur in this._data) {
  62573. var val = this._data[cur];
  62574. var res = callback(cur, val);
  62575. if (res) {
  62576. return res;
  62577. }
  62578. }
  62579. return null;
  62580. };
  62581. return StringDictionary;
  62582. }());
  62583. BABYLON.StringDictionary = StringDictionary;
  62584. })(BABYLON || (BABYLON = {}));
  62585. //# sourceMappingURL=babylon.stringDictionary.js.map
  62586. var BABYLON;
  62587. (function (BABYLON) {
  62588. var Tags = /** @class */ (function () {
  62589. function Tags() {
  62590. }
  62591. Tags.EnableFor = function (obj) {
  62592. obj._tags = obj._tags || {};
  62593. obj.hasTags = function () {
  62594. return Tags.HasTags(obj);
  62595. };
  62596. obj.addTags = function (tagsString) {
  62597. return Tags.AddTagsTo(obj, tagsString);
  62598. };
  62599. obj.removeTags = function (tagsString) {
  62600. return Tags.RemoveTagsFrom(obj, tagsString);
  62601. };
  62602. obj.matchesTagsQuery = function (tagsQuery) {
  62603. return Tags.MatchesQuery(obj, tagsQuery);
  62604. };
  62605. };
  62606. Tags.DisableFor = function (obj) {
  62607. delete obj._tags;
  62608. delete obj.hasTags;
  62609. delete obj.addTags;
  62610. delete obj.removeTags;
  62611. delete obj.matchesTagsQuery;
  62612. };
  62613. Tags.HasTags = function (obj) {
  62614. if (!obj._tags) {
  62615. return false;
  62616. }
  62617. return !BABYLON.Tools.IsEmpty(obj._tags);
  62618. };
  62619. Tags.GetTags = function (obj, asString) {
  62620. if (asString === void 0) { asString = true; }
  62621. if (!obj._tags) {
  62622. return null;
  62623. }
  62624. if (asString) {
  62625. var tagsArray = [];
  62626. for (var tag in obj._tags) {
  62627. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  62628. tagsArray.push(tag);
  62629. }
  62630. }
  62631. return tagsArray.join(" ");
  62632. }
  62633. else {
  62634. return obj._tags;
  62635. }
  62636. };
  62637. // the tags 'true' and 'false' are reserved and cannot be used as tags
  62638. // a tag cannot start with '||', '&&', and '!'
  62639. // it cannot contain whitespaces
  62640. Tags.AddTagsTo = function (obj, tagsString) {
  62641. if (!tagsString) {
  62642. return;
  62643. }
  62644. if (typeof tagsString !== "string") {
  62645. return;
  62646. }
  62647. var tags = tagsString.split(" ");
  62648. tags.forEach(function (tag, index, array) {
  62649. Tags._AddTagTo(obj, tag);
  62650. });
  62651. };
  62652. Tags._AddTagTo = function (obj, tag) {
  62653. tag = tag.trim();
  62654. if (tag === "" || tag === "true" || tag === "false") {
  62655. return;
  62656. }
  62657. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  62658. return;
  62659. }
  62660. Tags.EnableFor(obj);
  62661. obj._tags[tag] = true;
  62662. };
  62663. Tags.RemoveTagsFrom = function (obj, tagsString) {
  62664. if (!Tags.HasTags(obj)) {
  62665. return;
  62666. }
  62667. var tags = tagsString.split(" ");
  62668. for (var t in tags) {
  62669. Tags._RemoveTagFrom(obj, tags[t]);
  62670. }
  62671. };
  62672. Tags._RemoveTagFrom = function (obj, tag) {
  62673. delete obj._tags[tag];
  62674. };
  62675. Tags.MatchesQuery = function (obj, tagsQuery) {
  62676. if (tagsQuery === undefined) {
  62677. return true;
  62678. }
  62679. if (tagsQuery === "") {
  62680. return Tags.HasTags(obj);
  62681. }
  62682. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  62683. };
  62684. return Tags;
  62685. }());
  62686. BABYLON.Tags = Tags;
  62687. })(BABYLON || (BABYLON = {}));
  62688. //# sourceMappingURL=babylon.tags.js.map
  62689. var BABYLON;
  62690. (function (BABYLON) {
  62691. var AndOrNotEvaluator = /** @class */ (function () {
  62692. function AndOrNotEvaluator() {
  62693. }
  62694. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  62695. if (!query.match(/\([^\(\)]*\)/g)) {
  62696. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  62697. }
  62698. else {
  62699. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  62700. // remove parenthesis
  62701. r = r.slice(1, r.length - 1);
  62702. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  62703. });
  62704. }
  62705. if (query === "true") {
  62706. return true;
  62707. }
  62708. if (query === "false") {
  62709. return false;
  62710. }
  62711. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  62712. };
  62713. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  62714. evaluateCallback = evaluateCallback || (function (r) {
  62715. return r === "true" ? true : false;
  62716. });
  62717. var result;
  62718. var or = parenthesisContent.split("||");
  62719. for (var i in or) {
  62720. if (or.hasOwnProperty(i)) {
  62721. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  62722. var and = ori.split("&&");
  62723. if (and.length > 1) {
  62724. for (var j = 0; j < and.length; ++j) {
  62725. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  62726. if (andj !== "true" && andj !== "false") {
  62727. if (andj[0] === "!") {
  62728. result = !evaluateCallback(andj.substring(1));
  62729. }
  62730. else {
  62731. result = evaluateCallback(andj);
  62732. }
  62733. }
  62734. else {
  62735. result = andj === "true" ? true : false;
  62736. }
  62737. if (!result) {
  62738. ori = "false";
  62739. break;
  62740. }
  62741. }
  62742. }
  62743. if (result || ori === "true") {
  62744. result = true;
  62745. break;
  62746. }
  62747. // result equals false (or undefined)
  62748. if (ori !== "true" && ori !== "false") {
  62749. if (ori[0] === "!") {
  62750. result = !evaluateCallback(ori.substring(1));
  62751. }
  62752. else {
  62753. result = evaluateCallback(ori);
  62754. }
  62755. }
  62756. else {
  62757. result = ori === "true" ? true : false;
  62758. }
  62759. }
  62760. }
  62761. // the whole parenthesis scope is replaced by 'true' or 'false'
  62762. return result ? "true" : "false";
  62763. };
  62764. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  62765. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  62766. // remove whitespaces
  62767. r = r.replace(/[\s]/g, function () { return ""; });
  62768. return r.length % 2 ? "!" : "";
  62769. });
  62770. booleanString = booleanString.trim();
  62771. if (booleanString === "!true") {
  62772. booleanString = "false";
  62773. }
  62774. else if (booleanString === "!false") {
  62775. booleanString = "true";
  62776. }
  62777. return booleanString;
  62778. };
  62779. return AndOrNotEvaluator;
  62780. }());
  62781. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  62782. })(BABYLON || (BABYLON = {}));
  62783. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  62784. var BABYLON;
  62785. (function (BABYLON) {
  62786. var Database = /** @class */ (function () {
  62787. function Database(urlToScene, callbackManifestChecked) {
  62788. // Handling various flavors of prefixed version of IndexedDB
  62789. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  62790. this.callbackManifestChecked = callbackManifestChecked;
  62791. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  62792. this.db = null;
  62793. this._enableSceneOffline = false;
  62794. this._enableTexturesOffline = false;
  62795. this.manifestVersionFound = 0;
  62796. this.mustUpdateRessources = false;
  62797. this.hasReachedQuota = false;
  62798. if (!Database.IDBStorageEnabled) {
  62799. this.callbackManifestChecked(true);
  62800. }
  62801. else {
  62802. this.checkManifestFile();
  62803. }
  62804. }
  62805. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  62806. get: function () {
  62807. return this._enableSceneOffline;
  62808. },
  62809. enumerable: true,
  62810. configurable: true
  62811. });
  62812. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  62813. get: function () {
  62814. return this._enableTexturesOffline;
  62815. },
  62816. enumerable: true,
  62817. configurable: true
  62818. });
  62819. Database.prototype.checkManifestFile = function () {
  62820. var _this = this;
  62821. var noManifestFile = function () {
  62822. _this._enableSceneOffline = false;
  62823. _this._enableTexturesOffline = false;
  62824. _this.callbackManifestChecked(false);
  62825. };
  62826. var timeStampUsed = false;
  62827. var manifestURL = this.currentSceneUrl + ".manifest";
  62828. var xhr = new XMLHttpRequest();
  62829. if (navigator.onLine) {
  62830. // Adding a timestamp to by-pass browsers' cache
  62831. timeStampUsed = true;
  62832. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  62833. }
  62834. xhr.open("GET", manifestURL, true);
  62835. xhr.addEventListener("load", function () {
  62836. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  62837. try {
  62838. var manifestFile = JSON.parse(xhr.response);
  62839. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  62840. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  62841. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  62842. _this.manifestVersionFound = manifestFile.version;
  62843. }
  62844. if (_this.callbackManifestChecked) {
  62845. _this.callbackManifestChecked(true);
  62846. }
  62847. }
  62848. catch (ex) {
  62849. noManifestFile();
  62850. }
  62851. }
  62852. else {
  62853. noManifestFile();
  62854. }
  62855. }, false);
  62856. xhr.addEventListener("error", function (event) {
  62857. if (timeStampUsed) {
  62858. timeStampUsed = false;
  62859. // Let's retry without the timeStamp
  62860. // It could fail when coupled with HTML5 Offline API
  62861. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  62862. xhr.open("GET", retryManifestURL, true);
  62863. xhr.send();
  62864. }
  62865. else {
  62866. noManifestFile();
  62867. }
  62868. }, false);
  62869. try {
  62870. xhr.send();
  62871. }
  62872. catch (ex) {
  62873. BABYLON.Tools.Error("Error on XHR send request.");
  62874. this.callbackManifestChecked(false);
  62875. }
  62876. };
  62877. Database.prototype.openAsync = function (successCallback, errorCallback) {
  62878. var _this = this;
  62879. var handleError = function () {
  62880. _this.isSupported = false;
  62881. if (errorCallback)
  62882. errorCallback();
  62883. };
  62884. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  62885. // Your browser doesn't support IndexedDB
  62886. this.isSupported = false;
  62887. if (errorCallback)
  62888. errorCallback();
  62889. }
  62890. else {
  62891. // If the DB hasn't been opened or created yet
  62892. if (!this.db) {
  62893. this.hasReachedQuota = false;
  62894. this.isSupported = true;
  62895. var request = this.idbFactory.open("babylonjs", 1);
  62896. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  62897. request.onerror = function (event) {
  62898. handleError();
  62899. };
  62900. // executes when a version change transaction cannot complete due to other active transactions
  62901. request.onblocked = function (event) {
  62902. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  62903. handleError();
  62904. };
  62905. // DB has been opened successfully
  62906. request.onsuccess = function (event) {
  62907. _this.db = request.result;
  62908. successCallback();
  62909. };
  62910. // Initialization of the DB. Creating Scenes & Textures stores
  62911. request.onupgradeneeded = function (event) {
  62912. _this.db = (event.target).result;
  62913. if (_this.db) {
  62914. try {
  62915. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  62916. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  62917. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  62918. }
  62919. catch (ex) {
  62920. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  62921. handleError();
  62922. }
  62923. }
  62924. };
  62925. }
  62926. else {
  62927. if (successCallback)
  62928. successCallback();
  62929. }
  62930. }
  62931. };
  62932. Database.prototype.loadImageFromDB = function (url, image) {
  62933. var _this = this;
  62934. var completeURL = Database.ReturnFullUrlLocation(url);
  62935. var saveAndLoadImage = function () {
  62936. if (!_this.hasReachedQuota && _this.db !== null) {
  62937. // the texture is not yet in the DB, let's try to save it
  62938. _this._saveImageIntoDBAsync(completeURL, image);
  62939. }
  62940. else {
  62941. image.src = url;
  62942. }
  62943. };
  62944. if (!this.mustUpdateRessources) {
  62945. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  62946. }
  62947. else {
  62948. saveAndLoadImage();
  62949. }
  62950. };
  62951. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  62952. if (this.isSupported && this.db !== null) {
  62953. var texture;
  62954. var transaction = this.db.transaction(["textures"]);
  62955. transaction.onabort = function (event) {
  62956. image.src = url;
  62957. };
  62958. transaction.oncomplete = function (event) {
  62959. var blobTextureURL;
  62960. if (texture) {
  62961. var URL = window.URL || window.webkitURL;
  62962. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  62963. image.onerror = function () {
  62964. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  62965. image.src = url;
  62966. };
  62967. image.src = blobTextureURL;
  62968. }
  62969. else {
  62970. notInDBCallback();
  62971. }
  62972. };
  62973. var getRequest = transaction.objectStore("textures").get(url);
  62974. getRequest.onsuccess = function (event) {
  62975. texture = (event.target).result;
  62976. };
  62977. getRequest.onerror = function (event) {
  62978. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  62979. image.src = url;
  62980. };
  62981. }
  62982. else {
  62983. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62984. image.src = url;
  62985. }
  62986. };
  62987. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  62988. var _this = this;
  62989. if (this.isSupported) {
  62990. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  62991. var generateBlobUrl = function () {
  62992. var blobTextureURL;
  62993. if (blob) {
  62994. var URL = window.URL || window.webkitURL;
  62995. try {
  62996. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  62997. }
  62998. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  62999. catch (ex) {
  63000. blobTextureURL = URL.createObjectURL(blob);
  63001. }
  63002. }
  63003. if (blobTextureURL) {
  63004. image.src = blobTextureURL;
  63005. }
  63006. };
  63007. if (Database.IsUASupportingBlobStorage) {
  63008. var xhr = new XMLHttpRequest(), blob;
  63009. xhr.open("GET", url, true);
  63010. xhr.responseType = "blob";
  63011. xhr.addEventListener("load", function () {
  63012. if (xhr.status === 200 && _this.db) {
  63013. // Blob as response (XHR2)
  63014. blob = xhr.response;
  63015. var transaction = _this.db.transaction(["textures"], "readwrite");
  63016. // the transaction could abort because of a QuotaExceededError error
  63017. transaction.onabort = function (event) {
  63018. try {
  63019. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  63020. var srcElement = (event.srcElement || event.target);
  63021. var error = srcElement.error;
  63022. if (error && error.name === "QuotaExceededError") {
  63023. _this.hasReachedQuota = true;
  63024. }
  63025. }
  63026. catch (ex) { }
  63027. generateBlobUrl();
  63028. };
  63029. transaction.oncomplete = function (event) {
  63030. generateBlobUrl();
  63031. };
  63032. var newTexture = { textureUrl: url, data: blob };
  63033. try {
  63034. // Put the blob into the dabase
  63035. var addRequest = transaction.objectStore("textures").put(newTexture);
  63036. addRequest.onsuccess = function (event) {
  63037. };
  63038. addRequest.onerror = function (event) {
  63039. generateBlobUrl();
  63040. };
  63041. }
  63042. catch (ex) {
  63043. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  63044. if (ex.code === 25) {
  63045. Database.IsUASupportingBlobStorage = false;
  63046. }
  63047. image.src = url;
  63048. }
  63049. }
  63050. else {
  63051. image.src = url;
  63052. }
  63053. }, false);
  63054. xhr.addEventListener("error", function (event) {
  63055. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  63056. image.src = url;
  63057. }, false);
  63058. xhr.send();
  63059. }
  63060. else {
  63061. image.src = url;
  63062. }
  63063. }
  63064. else {
  63065. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63066. image.src = url;
  63067. }
  63068. };
  63069. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  63070. var _this = this;
  63071. var updateVersion = function () {
  63072. // the version is not yet in the DB or we need to update it
  63073. _this._saveVersionIntoDBAsync(url, versionLoaded);
  63074. };
  63075. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  63076. };
  63077. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  63078. var _this = this;
  63079. if (this.isSupported && this.db) {
  63080. var version;
  63081. try {
  63082. var transaction = this.db.transaction(["versions"]);
  63083. transaction.oncomplete = function (event) {
  63084. if (version) {
  63085. // If the version in the JSON file is > than the version in DB
  63086. if (_this.manifestVersionFound > version.data) {
  63087. _this.mustUpdateRessources = true;
  63088. updateInDBCallback();
  63089. }
  63090. else {
  63091. callback(version.data);
  63092. }
  63093. }
  63094. else {
  63095. _this.mustUpdateRessources = true;
  63096. updateInDBCallback();
  63097. }
  63098. };
  63099. transaction.onabort = function (event) {
  63100. callback(-1);
  63101. };
  63102. var getRequest = transaction.objectStore("versions").get(url);
  63103. getRequest.onsuccess = function (event) {
  63104. version = (event.target).result;
  63105. };
  63106. getRequest.onerror = function (event) {
  63107. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  63108. callback(-1);
  63109. };
  63110. }
  63111. catch (ex) {
  63112. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  63113. callback(-1);
  63114. }
  63115. }
  63116. else {
  63117. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63118. callback(-1);
  63119. }
  63120. };
  63121. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  63122. var _this = this;
  63123. if (this.isSupported && !this.hasReachedQuota && this.db) {
  63124. try {
  63125. // Open a transaction to the database
  63126. var transaction = this.db.transaction(["versions"], "readwrite");
  63127. // the transaction could abort because of a QuotaExceededError error
  63128. transaction.onabort = function (event) {
  63129. try {
  63130. var error = event.srcElement['error'];
  63131. if (error && error.name === "QuotaExceededError") {
  63132. _this.hasReachedQuota = true;
  63133. }
  63134. }
  63135. catch (ex) { }
  63136. callback(-1);
  63137. };
  63138. transaction.oncomplete = function (event) {
  63139. callback(_this.manifestVersionFound);
  63140. };
  63141. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  63142. // Put the scene into the database
  63143. var addRequest = transaction.objectStore("versions").put(newVersion);
  63144. addRequest.onsuccess = function (event) {
  63145. };
  63146. addRequest.onerror = function (event) {
  63147. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  63148. };
  63149. }
  63150. catch (ex) {
  63151. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  63152. callback(-1);
  63153. }
  63154. }
  63155. else {
  63156. callback(-1);
  63157. }
  63158. };
  63159. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  63160. var _this = this;
  63161. var completeUrl = Database.ReturnFullUrlLocation(url);
  63162. var saveAndLoadFile = function () {
  63163. // the scene is not yet in the DB, let's try to save it
  63164. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  63165. };
  63166. this._checkVersionFromDB(completeUrl, function (version) {
  63167. if (version !== -1) {
  63168. if (!_this.mustUpdateRessources) {
  63169. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  63170. }
  63171. else {
  63172. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  63173. }
  63174. }
  63175. else {
  63176. if (errorCallback) {
  63177. errorCallback();
  63178. }
  63179. }
  63180. });
  63181. };
  63182. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  63183. if (this.isSupported && this.db) {
  63184. var targetStore;
  63185. if (url.indexOf(".babylon") !== -1) {
  63186. targetStore = "scenes";
  63187. }
  63188. else {
  63189. targetStore = "textures";
  63190. }
  63191. var file;
  63192. var transaction = this.db.transaction([targetStore]);
  63193. transaction.oncomplete = function (event) {
  63194. if (file) {
  63195. callback(file.data);
  63196. }
  63197. else {
  63198. notInDBCallback();
  63199. }
  63200. };
  63201. transaction.onabort = function (event) {
  63202. notInDBCallback();
  63203. };
  63204. var getRequest = transaction.objectStore(targetStore).get(url);
  63205. getRequest.onsuccess = function (event) {
  63206. file = (event.target).result;
  63207. };
  63208. getRequest.onerror = function (event) {
  63209. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  63210. notInDBCallback();
  63211. };
  63212. }
  63213. else {
  63214. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63215. callback();
  63216. }
  63217. };
  63218. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  63219. var _this = this;
  63220. if (this.isSupported) {
  63221. var targetStore;
  63222. if (url.indexOf(".babylon") !== -1) {
  63223. targetStore = "scenes";
  63224. }
  63225. else {
  63226. targetStore = "textures";
  63227. }
  63228. // Create XHR
  63229. var xhr = new XMLHttpRequest();
  63230. var fileData;
  63231. xhr.open("GET", url, true);
  63232. if (useArrayBuffer) {
  63233. xhr.responseType = "arraybuffer";
  63234. }
  63235. if (progressCallback) {
  63236. xhr.onprogress = progressCallback;
  63237. }
  63238. xhr.addEventListener("load", function () {
  63239. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  63240. // Blob as response (XHR2)
  63241. //fileData = xhr.responseText;
  63242. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  63243. if (!_this.hasReachedQuota && _this.db) {
  63244. // Open a transaction to the database
  63245. var transaction = _this.db.transaction([targetStore], "readwrite");
  63246. // the transaction could abort because of a QuotaExceededError error
  63247. transaction.onabort = function (event) {
  63248. try {
  63249. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  63250. var error = event.srcElement['error'];
  63251. if (error && error.name === "QuotaExceededError") {
  63252. _this.hasReachedQuota = true;
  63253. }
  63254. }
  63255. catch (ex) { }
  63256. callback(fileData);
  63257. };
  63258. transaction.oncomplete = function (event) {
  63259. callback(fileData);
  63260. };
  63261. var newFile;
  63262. if (targetStore === "scenes") {
  63263. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  63264. }
  63265. else {
  63266. newFile = { textureUrl: url, data: fileData };
  63267. }
  63268. try {
  63269. // Put the scene into the database
  63270. var addRequest = transaction.objectStore(targetStore).put(newFile);
  63271. addRequest.onsuccess = function (event) {
  63272. };
  63273. addRequest.onerror = function (event) {
  63274. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  63275. };
  63276. }
  63277. catch (ex) {
  63278. callback(fileData);
  63279. }
  63280. }
  63281. else {
  63282. callback(fileData);
  63283. }
  63284. }
  63285. else {
  63286. callback();
  63287. }
  63288. }, false);
  63289. xhr.addEventListener("error", function (event) {
  63290. BABYLON.Tools.Error("error on XHR request.");
  63291. callback();
  63292. }, false);
  63293. xhr.send();
  63294. }
  63295. else {
  63296. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63297. callback();
  63298. }
  63299. };
  63300. Database.IsUASupportingBlobStorage = true;
  63301. Database.IDBStorageEnabled = true;
  63302. Database.parseURL = function (url) {
  63303. var a = document.createElement('a');
  63304. a.href = url;
  63305. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  63306. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  63307. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  63308. return absLocation;
  63309. };
  63310. Database.ReturnFullUrlLocation = function (url) {
  63311. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  63312. return (Database.parseURL(window.location.href) + url);
  63313. }
  63314. else {
  63315. return url;
  63316. }
  63317. };
  63318. return Database;
  63319. }());
  63320. BABYLON.Database = Database;
  63321. })(BABYLON || (BABYLON = {}));
  63322. //# sourceMappingURL=babylon.database.js.map
  63323. var BABYLON;
  63324. (function (BABYLON) {
  63325. var FresnelParameters = /** @class */ (function () {
  63326. function FresnelParameters() {
  63327. this._isEnabled = true;
  63328. this.leftColor = BABYLON.Color3.White();
  63329. this.rightColor = BABYLON.Color3.Black();
  63330. this.bias = 0;
  63331. this.power = 1;
  63332. }
  63333. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  63334. get: function () {
  63335. return this._isEnabled;
  63336. },
  63337. set: function (value) {
  63338. if (this._isEnabled === value) {
  63339. return;
  63340. }
  63341. this._isEnabled = value;
  63342. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  63343. },
  63344. enumerable: true,
  63345. configurable: true
  63346. });
  63347. FresnelParameters.prototype.clone = function () {
  63348. var newFresnelParameters = new FresnelParameters();
  63349. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  63350. return newFresnelParameters;
  63351. };
  63352. FresnelParameters.prototype.serialize = function () {
  63353. var serializationObject = {};
  63354. serializationObject.isEnabled = this.isEnabled;
  63355. serializationObject.leftColor = this.leftColor;
  63356. serializationObject.rightColor = this.rightColor;
  63357. serializationObject.bias = this.bias;
  63358. serializationObject.power = this.power;
  63359. return serializationObject;
  63360. };
  63361. FresnelParameters.Parse = function (parsedFresnelParameters) {
  63362. var fresnelParameters = new FresnelParameters();
  63363. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  63364. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  63365. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  63366. fresnelParameters.bias = parsedFresnelParameters.bias;
  63367. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  63368. return fresnelParameters;
  63369. };
  63370. return FresnelParameters;
  63371. }());
  63372. BABYLON.FresnelParameters = FresnelParameters;
  63373. })(BABYLON || (BABYLON = {}));
  63374. //# sourceMappingURL=babylon.fresnelParameters.js.map
  63375. var BABYLON;
  63376. (function (BABYLON) {
  63377. var MultiMaterial = /** @class */ (function (_super) {
  63378. __extends(MultiMaterial, _super);
  63379. function MultiMaterial(name, scene) {
  63380. var _this = _super.call(this, name, scene, true) || this;
  63381. scene.multiMaterials.push(_this);
  63382. _this.subMaterials = new Array();
  63383. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  63384. return _this;
  63385. }
  63386. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  63387. get: function () {
  63388. return this._subMaterials;
  63389. },
  63390. set: function (value) {
  63391. this._subMaterials = value;
  63392. this._hookArray(value);
  63393. },
  63394. enumerable: true,
  63395. configurable: true
  63396. });
  63397. MultiMaterial.prototype._hookArray = function (array) {
  63398. var _this = this;
  63399. var oldPush = array.push;
  63400. array.push = function () {
  63401. var items = [];
  63402. for (var _i = 0; _i < arguments.length; _i++) {
  63403. items[_i] = arguments[_i];
  63404. }
  63405. var result = oldPush.apply(array, items);
  63406. _this._markAllSubMeshesAsTexturesDirty();
  63407. return result;
  63408. };
  63409. var oldSplice = array.splice;
  63410. array.splice = function (index, deleteCount) {
  63411. var deleted = oldSplice.apply(array, [index, deleteCount]);
  63412. _this._markAllSubMeshesAsTexturesDirty();
  63413. return deleted;
  63414. };
  63415. };
  63416. // Properties
  63417. MultiMaterial.prototype.getSubMaterial = function (index) {
  63418. if (index < 0 || index >= this.subMaterials.length) {
  63419. return this.getScene().defaultMaterial;
  63420. }
  63421. return this.subMaterials[index];
  63422. };
  63423. MultiMaterial.prototype.getActiveTextures = function () {
  63424. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  63425. if (subMaterial) {
  63426. return subMaterial.getActiveTextures();
  63427. }
  63428. else {
  63429. return [];
  63430. }
  63431. }));
  63432. var _a;
  63433. };
  63434. // Methods
  63435. MultiMaterial.prototype.getClassName = function () {
  63436. return "MultiMaterial";
  63437. };
  63438. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  63439. for (var index = 0; index < this.subMaterials.length; index++) {
  63440. var subMaterial = this.subMaterials[index];
  63441. if (subMaterial) {
  63442. if (subMaterial.storeEffectOnSubMeshes) {
  63443. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  63444. return false;
  63445. }
  63446. continue;
  63447. }
  63448. if (!subMaterial.isReady(mesh)) {
  63449. return false;
  63450. }
  63451. }
  63452. }
  63453. return true;
  63454. };
  63455. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  63456. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  63457. for (var index = 0; index < this.subMaterials.length; index++) {
  63458. var subMaterial = null;
  63459. var current = this.subMaterials[index];
  63460. if (cloneChildren && current) {
  63461. subMaterial = current.clone(name + "-" + current.name);
  63462. }
  63463. else {
  63464. subMaterial = this.subMaterials[index];
  63465. }
  63466. newMultiMaterial.subMaterials.push(subMaterial);
  63467. }
  63468. return newMultiMaterial;
  63469. };
  63470. MultiMaterial.prototype.serialize = function () {
  63471. var serializationObject = {};
  63472. serializationObject.name = this.name;
  63473. serializationObject.id = this.id;
  63474. if (BABYLON.Tags) {
  63475. serializationObject.tags = BABYLON.Tags.GetTags(this);
  63476. }
  63477. serializationObject.materials = [];
  63478. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  63479. var subMat = this.subMaterials[matIndex];
  63480. if (subMat) {
  63481. serializationObject.materials.push(subMat.id);
  63482. }
  63483. else {
  63484. serializationObject.materials.push(null);
  63485. }
  63486. }
  63487. return serializationObject;
  63488. };
  63489. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  63490. var scene = this.getScene();
  63491. if (!scene) {
  63492. return;
  63493. }
  63494. var index = scene.multiMaterials.indexOf(this);
  63495. if (index >= 0) {
  63496. scene.multiMaterials.splice(index, 1);
  63497. }
  63498. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  63499. };
  63500. return MultiMaterial;
  63501. }(BABYLON.Material));
  63502. BABYLON.MultiMaterial = MultiMaterial;
  63503. })(BABYLON || (BABYLON = {}));
  63504. //# sourceMappingURL=babylon.multiMaterial.js.map
  63505. var BABYLON;
  63506. (function (BABYLON) {
  63507. var FreeCameraTouchInput = /** @class */ (function () {
  63508. function FreeCameraTouchInput() {
  63509. this._offsetX = null;
  63510. this._offsetY = null;
  63511. this._pointerPressed = new Array();
  63512. this.touchAngularSensibility = 200000.0;
  63513. this.touchMoveSensibility = 250.0;
  63514. }
  63515. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  63516. var _this = this;
  63517. var previousPosition = null;
  63518. if (this._pointerInput === undefined) {
  63519. this._onLostFocus = function (evt) {
  63520. _this._offsetX = null;
  63521. _this._offsetY = null;
  63522. };
  63523. this._pointerInput = function (p, s) {
  63524. var evt = p.event;
  63525. if (evt.pointerType === "mouse") {
  63526. return;
  63527. }
  63528. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  63529. if (!noPreventDefault) {
  63530. evt.preventDefault();
  63531. }
  63532. _this._pointerPressed.push(evt.pointerId);
  63533. if (_this._pointerPressed.length !== 1) {
  63534. return;
  63535. }
  63536. previousPosition = {
  63537. x: evt.clientX,
  63538. y: evt.clientY
  63539. };
  63540. }
  63541. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  63542. if (!noPreventDefault) {
  63543. evt.preventDefault();
  63544. }
  63545. var index = _this._pointerPressed.indexOf(evt.pointerId);
  63546. if (index === -1) {
  63547. return;
  63548. }
  63549. _this._pointerPressed.splice(index, 1);
  63550. if (index != 0) {
  63551. return;
  63552. }
  63553. previousPosition = null;
  63554. _this._offsetX = null;
  63555. _this._offsetY = null;
  63556. }
  63557. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  63558. if (!noPreventDefault) {
  63559. evt.preventDefault();
  63560. }
  63561. if (!previousPosition) {
  63562. return;
  63563. }
  63564. var index = _this._pointerPressed.indexOf(evt.pointerId);
  63565. if (index != 0) {
  63566. return;
  63567. }
  63568. _this._offsetX = evt.clientX - previousPosition.x;
  63569. _this._offsetY = -(evt.clientY - previousPosition.y);
  63570. }
  63571. };
  63572. }
  63573. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  63574. if (this._onLostFocus) {
  63575. element.addEventListener("blur", this._onLostFocus);
  63576. }
  63577. };
  63578. FreeCameraTouchInput.prototype.detachControl = function (element) {
  63579. if (this._pointerInput && element) {
  63580. if (this._observer) {
  63581. this.camera.getScene().onPointerObservable.remove(this._observer);
  63582. this._observer = null;
  63583. }
  63584. if (this._onLostFocus) {
  63585. element.removeEventListener("blur", this._onLostFocus);
  63586. this._onLostFocus = null;
  63587. }
  63588. this._pointerPressed = [];
  63589. this._offsetX = null;
  63590. this._offsetY = null;
  63591. }
  63592. };
  63593. FreeCameraTouchInput.prototype.checkInputs = function () {
  63594. if (this._offsetX && this._offsetY) {
  63595. var camera = this.camera;
  63596. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  63597. if (this._pointerPressed.length > 1) {
  63598. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  63599. }
  63600. else {
  63601. var speed = camera._computeLocalCameraSpeed();
  63602. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  63603. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  63604. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  63605. }
  63606. }
  63607. };
  63608. FreeCameraTouchInput.prototype.getClassName = function () {
  63609. return "FreeCameraTouchInput";
  63610. };
  63611. FreeCameraTouchInput.prototype.getSimpleName = function () {
  63612. return "touch";
  63613. };
  63614. __decorate([
  63615. BABYLON.serialize()
  63616. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  63617. __decorate([
  63618. BABYLON.serialize()
  63619. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  63620. return FreeCameraTouchInput;
  63621. }());
  63622. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  63623. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  63624. })(BABYLON || (BABYLON = {}));
  63625. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  63626. var BABYLON;
  63627. (function (BABYLON) {
  63628. // We're mainly based on the logic defined into the FreeCamera code
  63629. var TouchCamera = /** @class */ (function (_super) {
  63630. __extends(TouchCamera, _super);
  63631. //-- end properties for backward compatibility for inputs
  63632. function TouchCamera(name, position, scene) {
  63633. var _this = _super.call(this, name, position, scene) || this;
  63634. _this.inputs.addTouch();
  63635. _this._setupInputs();
  63636. return _this;
  63637. }
  63638. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  63639. //-- Begin properties for backward compatibility for inputs
  63640. get: function () {
  63641. var touch = this.inputs.attached["touch"];
  63642. if (touch)
  63643. return touch.touchAngularSensibility;
  63644. return 0;
  63645. },
  63646. set: function (value) {
  63647. var touch = this.inputs.attached["touch"];
  63648. if (touch)
  63649. touch.touchAngularSensibility = value;
  63650. },
  63651. enumerable: true,
  63652. configurable: true
  63653. });
  63654. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  63655. get: function () {
  63656. var touch = this.inputs.attached["touch"];
  63657. if (touch)
  63658. return touch.touchMoveSensibility;
  63659. return 0;
  63660. },
  63661. set: function (value) {
  63662. var touch = this.inputs.attached["touch"];
  63663. if (touch)
  63664. touch.touchMoveSensibility = value;
  63665. },
  63666. enumerable: true,
  63667. configurable: true
  63668. });
  63669. TouchCamera.prototype.getClassName = function () {
  63670. return "TouchCamera";
  63671. };
  63672. TouchCamera.prototype._setupInputs = function () {
  63673. var mouse = this.inputs.attached["mouse"];
  63674. if (mouse) {
  63675. mouse.touchEnabled = false;
  63676. }
  63677. };
  63678. return TouchCamera;
  63679. }(BABYLON.FreeCamera));
  63680. BABYLON.TouchCamera = TouchCamera;
  63681. })(BABYLON || (BABYLON = {}));
  63682. //# sourceMappingURL=babylon.touchCamera.js.map
  63683. var BABYLON;
  63684. (function (BABYLON) {
  63685. var ProceduralTexture = /** @class */ (function (_super) {
  63686. __extends(ProceduralTexture, _super);
  63687. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  63688. if (fallbackTexture === void 0) { fallbackTexture = null; }
  63689. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63690. if (isCube === void 0) { isCube = false; }
  63691. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63692. _this.isCube = isCube;
  63693. _this.isEnabled = true;
  63694. _this._currentRefreshId = -1;
  63695. _this._refreshRate = 1;
  63696. _this._vertexBuffers = {};
  63697. _this._uniforms = new Array();
  63698. _this._samplers = new Array();
  63699. _this._textures = {};
  63700. _this._floats = {};
  63701. _this._floatsArrays = {};
  63702. _this._colors3 = {};
  63703. _this._colors4 = {};
  63704. _this._vectors2 = {};
  63705. _this._vectors3 = {};
  63706. _this._matrices = {};
  63707. _this._fallbackTextureUsed = false;
  63708. scene._proceduralTextures.push(_this);
  63709. _this._engine = scene.getEngine();
  63710. _this.name = name;
  63711. _this.isRenderTarget = true;
  63712. _this._size = size;
  63713. _this._generateMipMaps = generateMipMaps;
  63714. _this.setFragment(fragment);
  63715. _this._fallbackTexture = fallbackTexture;
  63716. if (isCube) {
  63717. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  63718. _this.setFloat("face", 0);
  63719. }
  63720. else {
  63721. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  63722. }
  63723. // VBO
  63724. var vertices = [];
  63725. vertices.push(1, 1);
  63726. vertices.push(-1, 1);
  63727. vertices.push(-1, -1);
  63728. vertices.push(1, -1);
  63729. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  63730. _this._createIndexBuffer();
  63731. return _this;
  63732. }
  63733. ProceduralTexture.prototype._createIndexBuffer = function () {
  63734. var engine = this._engine;
  63735. // Indices
  63736. var indices = [];
  63737. indices.push(0);
  63738. indices.push(1);
  63739. indices.push(2);
  63740. indices.push(0);
  63741. indices.push(2);
  63742. indices.push(3);
  63743. this._indexBuffer = engine.createIndexBuffer(indices);
  63744. };
  63745. ProceduralTexture.prototype._rebuild = function () {
  63746. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63747. if (vb) {
  63748. vb._rebuild();
  63749. }
  63750. this._createIndexBuffer();
  63751. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63752. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63753. }
  63754. };
  63755. ProceduralTexture.prototype.reset = function () {
  63756. if (this._effect === undefined) {
  63757. return;
  63758. }
  63759. var engine = this._engine;
  63760. engine._releaseEffect(this._effect);
  63761. };
  63762. ProceduralTexture.prototype.isReady = function () {
  63763. var _this = this;
  63764. var engine = this._engine;
  63765. var shaders;
  63766. if (!this._fragment) {
  63767. return false;
  63768. }
  63769. if (this._fallbackTextureUsed) {
  63770. return true;
  63771. }
  63772. if (this._fragment.fragmentElement !== undefined) {
  63773. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  63774. }
  63775. else {
  63776. shaders = { vertex: "procedural", fragment: this._fragment };
  63777. }
  63778. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  63779. _this.releaseInternalTexture();
  63780. if (_this._fallbackTexture) {
  63781. _this._texture = _this._fallbackTexture._texture;
  63782. if (_this._texture) {
  63783. _this._texture.incrementReferences();
  63784. }
  63785. }
  63786. _this._fallbackTextureUsed = true;
  63787. });
  63788. return this._effect.isReady();
  63789. };
  63790. ProceduralTexture.prototype.resetRefreshCounter = function () {
  63791. this._currentRefreshId = -1;
  63792. };
  63793. ProceduralTexture.prototype.setFragment = function (fragment) {
  63794. this._fragment = fragment;
  63795. };
  63796. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  63797. get: function () {
  63798. return this._refreshRate;
  63799. },
  63800. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63801. set: function (value) {
  63802. this._refreshRate = value;
  63803. this.resetRefreshCounter();
  63804. },
  63805. enumerable: true,
  63806. configurable: true
  63807. });
  63808. ProceduralTexture.prototype._shouldRender = function () {
  63809. if (!this.isEnabled || !this.isReady() || !this._texture) {
  63810. return false;
  63811. }
  63812. if (this._fallbackTextureUsed) {
  63813. return false;
  63814. }
  63815. if (this._currentRefreshId === -1) {
  63816. this._currentRefreshId = 1;
  63817. return true;
  63818. }
  63819. if (this.refreshRate === this._currentRefreshId) {
  63820. this._currentRefreshId = 1;
  63821. return true;
  63822. }
  63823. this._currentRefreshId++;
  63824. return false;
  63825. };
  63826. ProceduralTexture.prototype.getRenderSize = function () {
  63827. return this._size;
  63828. };
  63829. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  63830. if (this._fallbackTextureUsed) {
  63831. return;
  63832. }
  63833. this.releaseInternalTexture();
  63834. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  63835. };
  63836. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  63837. if (this._uniforms.indexOf(uniformName) === -1) {
  63838. this._uniforms.push(uniformName);
  63839. }
  63840. };
  63841. ProceduralTexture.prototype.setTexture = function (name, texture) {
  63842. if (this._samplers.indexOf(name) === -1) {
  63843. this._samplers.push(name);
  63844. }
  63845. this._textures[name] = texture;
  63846. return this;
  63847. };
  63848. ProceduralTexture.prototype.setFloat = function (name, value) {
  63849. this._checkUniform(name);
  63850. this._floats[name] = value;
  63851. return this;
  63852. };
  63853. ProceduralTexture.prototype.setFloats = function (name, value) {
  63854. this._checkUniform(name);
  63855. this._floatsArrays[name] = value;
  63856. return this;
  63857. };
  63858. ProceduralTexture.prototype.setColor3 = function (name, value) {
  63859. this._checkUniform(name);
  63860. this._colors3[name] = value;
  63861. return this;
  63862. };
  63863. ProceduralTexture.prototype.setColor4 = function (name, value) {
  63864. this._checkUniform(name);
  63865. this._colors4[name] = value;
  63866. return this;
  63867. };
  63868. ProceduralTexture.prototype.setVector2 = function (name, value) {
  63869. this._checkUniform(name);
  63870. this._vectors2[name] = value;
  63871. return this;
  63872. };
  63873. ProceduralTexture.prototype.setVector3 = function (name, value) {
  63874. this._checkUniform(name);
  63875. this._vectors3[name] = value;
  63876. return this;
  63877. };
  63878. ProceduralTexture.prototype.setMatrix = function (name, value) {
  63879. this._checkUniform(name);
  63880. this._matrices[name] = value;
  63881. return this;
  63882. };
  63883. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  63884. var scene = this.getScene();
  63885. if (!scene) {
  63886. return;
  63887. }
  63888. var engine = this._engine;
  63889. // Render
  63890. engine.enableEffect(this._effect);
  63891. engine.setState(false);
  63892. // Texture
  63893. for (var name in this._textures) {
  63894. this._effect.setTexture(name, this._textures[name]);
  63895. }
  63896. // Float
  63897. for (name in this._floats) {
  63898. this._effect.setFloat(name, this._floats[name]);
  63899. }
  63900. // Floats
  63901. for (name in this._floatsArrays) {
  63902. this._effect.setArray(name, this._floatsArrays[name]);
  63903. }
  63904. // Color3
  63905. for (name in this._colors3) {
  63906. this._effect.setColor3(name, this._colors3[name]);
  63907. }
  63908. // Color4
  63909. for (name in this._colors4) {
  63910. var color = this._colors4[name];
  63911. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  63912. }
  63913. // Vector2
  63914. for (name in this._vectors2) {
  63915. this._effect.setVector2(name, this._vectors2[name]);
  63916. }
  63917. // Vector3
  63918. for (name in this._vectors3) {
  63919. this._effect.setVector3(name, this._vectors3[name]);
  63920. }
  63921. // Matrix
  63922. for (name in this._matrices) {
  63923. this._effect.setMatrix(name, this._matrices[name]);
  63924. }
  63925. if (!this._texture) {
  63926. return;
  63927. }
  63928. if (this.isCube) {
  63929. for (var face = 0; face < 6; face++) {
  63930. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  63931. // VBOs
  63932. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  63933. this._effect.setFloat("face", face);
  63934. // Clear
  63935. engine.clear(scene.clearColor, true, true, true);
  63936. // Draw order
  63937. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  63938. // Mipmaps
  63939. if (face === 5) {
  63940. engine.generateMipMapsForCubemap(this._texture);
  63941. }
  63942. }
  63943. }
  63944. else {
  63945. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  63946. // VBOs
  63947. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  63948. // Clear
  63949. engine.clear(scene.clearColor, true, true, true);
  63950. // Draw order
  63951. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  63952. }
  63953. // Unbind
  63954. engine.unBindFramebuffer(this._texture, this.isCube);
  63955. if (this.onGenerated) {
  63956. this.onGenerated();
  63957. }
  63958. };
  63959. ProceduralTexture.prototype.clone = function () {
  63960. var textureSize = this.getSize();
  63961. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  63962. // Base texture
  63963. newTexture.hasAlpha = this.hasAlpha;
  63964. newTexture.level = this.level;
  63965. // RenderTarget Texture
  63966. newTexture.coordinatesMode = this.coordinatesMode;
  63967. return newTexture;
  63968. };
  63969. ProceduralTexture.prototype.dispose = function () {
  63970. var scene = this.getScene();
  63971. if (!scene) {
  63972. return;
  63973. }
  63974. var index = scene._proceduralTextures.indexOf(this);
  63975. if (index >= 0) {
  63976. scene._proceduralTextures.splice(index, 1);
  63977. }
  63978. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63979. if (vertexBuffer) {
  63980. vertexBuffer.dispose();
  63981. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  63982. }
  63983. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  63984. this._indexBuffer = null;
  63985. }
  63986. _super.prototype.dispose.call(this);
  63987. };
  63988. return ProceduralTexture;
  63989. }(BABYLON.Texture));
  63990. BABYLON.ProceduralTexture = ProceduralTexture;
  63991. })(BABYLON || (BABYLON = {}));
  63992. //# sourceMappingURL=babylon.proceduralTexture.js.map
  63993. var BABYLON;
  63994. (function (BABYLON) {
  63995. var CustomProceduralTexture = /** @class */ (function (_super) {
  63996. __extends(CustomProceduralTexture, _super);
  63997. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  63998. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  63999. _this._animate = true;
  64000. _this._time = 0;
  64001. _this._texturePath = texturePath;
  64002. //Try to load json
  64003. _this.loadJson(texturePath);
  64004. _this.refreshRate = 1;
  64005. return _this;
  64006. }
  64007. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  64008. var _this = this;
  64009. var noConfigFile = function () {
  64010. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  64011. try {
  64012. _this.setFragment(_this._texturePath);
  64013. }
  64014. catch (ex) {
  64015. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  64016. }
  64017. };
  64018. var configFileUrl = jsonUrl + "/config.json";
  64019. var xhr = new XMLHttpRequest();
  64020. xhr.open("GET", configFileUrl, true);
  64021. xhr.addEventListener("load", function () {
  64022. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  64023. try {
  64024. _this._config = JSON.parse(xhr.response);
  64025. _this.updateShaderUniforms();
  64026. _this.updateTextures();
  64027. _this.setFragment(_this._texturePath + "/custom");
  64028. _this._animate = _this._config.animate;
  64029. _this.refreshRate = _this._config.refreshrate;
  64030. }
  64031. catch (ex) {
  64032. noConfigFile();
  64033. }
  64034. }
  64035. else {
  64036. noConfigFile();
  64037. }
  64038. }, false);
  64039. xhr.addEventListener("error", function () {
  64040. noConfigFile();
  64041. }, false);
  64042. try {
  64043. xhr.send();
  64044. }
  64045. catch (ex) {
  64046. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  64047. }
  64048. };
  64049. CustomProceduralTexture.prototype.isReady = function () {
  64050. if (!_super.prototype.isReady.call(this)) {
  64051. return false;
  64052. }
  64053. for (var name in this._textures) {
  64054. var texture = this._textures[name];
  64055. if (!texture.isReady()) {
  64056. return false;
  64057. }
  64058. }
  64059. return true;
  64060. };
  64061. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  64062. var scene = this.getScene();
  64063. if (this._animate && scene) {
  64064. this._time += scene.getAnimationRatio() * 0.03;
  64065. this.updateShaderUniforms();
  64066. }
  64067. _super.prototype.render.call(this, useCameraPostProcess);
  64068. };
  64069. CustomProceduralTexture.prototype.updateTextures = function () {
  64070. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  64071. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  64072. }
  64073. };
  64074. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  64075. if (this._config) {
  64076. for (var j = 0; j < this._config.uniforms.length; j++) {
  64077. var uniform = this._config.uniforms[j];
  64078. switch (uniform.type) {
  64079. case "float":
  64080. this.setFloat(uniform.name, uniform.value);
  64081. break;
  64082. case "color3":
  64083. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  64084. break;
  64085. case "color4":
  64086. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  64087. break;
  64088. case "vector2":
  64089. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  64090. break;
  64091. case "vector3":
  64092. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  64093. break;
  64094. }
  64095. }
  64096. }
  64097. this.setFloat("time", this._time);
  64098. };
  64099. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  64100. get: function () {
  64101. return this._animate;
  64102. },
  64103. set: function (value) {
  64104. this._animate = value;
  64105. },
  64106. enumerable: true,
  64107. configurable: true
  64108. });
  64109. return CustomProceduralTexture;
  64110. }(BABYLON.ProceduralTexture));
  64111. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  64112. })(BABYLON || (BABYLON = {}));
  64113. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  64114. var BABYLON;
  64115. (function (BABYLON) {
  64116. var FreeCameraGamepadInput = /** @class */ (function () {
  64117. function FreeCameraGamepadInput() {
  64118. this.gamepadAngularSensibility = 200;
  64119. this.gamepadMoveSensibility = 40;
  64120. // private members
  64121. this._cameraTransform = BABYLON.Matrix.Identity();
  64122. this._deltaTransform = BABYLON.Vector3.Zero();
  64123. this._vector3 = BABYLON.Vector3.Zero();
  64124. this._vector2 = BABYLON.Vector2.Zero();
  64125. }
  64126. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  64127. var _this = this;
  64128. var manager = this.camera.getScene().gamepadManager;
  64129. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  64130. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  64131. // prioritize XBOX gamepads.
  64132. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  64133. _this.gamepad = gamepad;
  64134. }
  64135. }
  64136. });
  64137. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  64138. if (_this.gamepad === gamepad) {
  64139. _this.gamepad = null;
  64140. }
  64141. });
  64142. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  64143. };
  64144. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  64145. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  64146. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  64147. this.gamepad = null;
  64148. };
  64149. FreeCameraGamepadInput.prototype.checkInputs = function () {
  64150. if (this.gamepad && this.gamepad.leftStick) {
  64151. var camera = this.camera;
  64152. var LSValues = this.gamepad.leftStick;
  64153. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  64154. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  64155. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  64156. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  64157. var RSValues = this.gamepad.rightStick;
  64158. if (RSValues) {
  64159. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  64160. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  64161. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  64162. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  64163. }
  64164. else {
  64165. RSValues = { x: 0, y: 0 };
  64166. }
  64167. if (!camera.rotationQuaternion) {
  64168. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  64169. }
  64170. else {
  64171. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  64172. }
  64173. var speed = camera._computeLocalCameraSpeed() * 50.0;
  64174. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  64175. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  64176. camera.cameraDirection.addInPlace(this._deltaTransform);
  64177. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  64178. camera.cameraRotation.addInPlace(this._vector2);
  64179. }
  64180. };
  64181. FreeCameraGamepadInput.prototype.getClassName = function () {
  64182. return "FreeCameraGamepadInput";
  64183. };
  64184. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  64185. return "gamepad";
  64186. };
  64187. __decorate([
  64188. BABYLON.serialize()
  64189. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  64190. __decorate([
  64191. BABYLON.serialize()
  64192. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  64193. return FreeCameraGamepadInput;
  64194. }());
  64195. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  64196. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  64197. })(BABYLON || (BABYLON = {}));
  64198. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  64199. var BABYLON;
  64200. (function (BABYLON) {
  64201. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  64202. function ArcRotateCameraGamepadInput() {
  64203. this.gamepadRotationSensibility = 80;
  64204. this.gamepadMoveSensibility = 40;
  64205. }
  64206. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  64207. var _this = this;
  64208. var manager = this.camera.getScene().gamepadManager;
  64209. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  64210. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  64211. // prioritize XBOX gamepads.
  64212. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  64213. _this.gamepad = gamepad;
  64214. }
  64215. }
  64216. });
  64217. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  64218. if (_this.gamepad === gamepad) {
  64219. _this.gamepad = null;
  64220. }
  64221. });
  64222. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  64223. };
  64224. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  64225. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  64226. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  64227. this.gamepad = null;
  64228. };
  64229. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  64230. if (this.gamepad) {
  64231. var camera = this.camera;
  64232. var RSValues = this.gamepad.rightStick;
  64233. if (RSValues) {
  64234. if (RSValues.x != 0) {
  64235. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  64236. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  64237. camera.inertialAlphaOffset += normalizedRX;
  64238. }
  64239. }
  64240. if (RSValues.y != 0) {
  64241. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  64242. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  64243. camera.inertialBetaOffset += normalizedRY;
  64244. }
  64245. }
  64246. }
  64247. var LSValues = this.gamepad.leftStick;
  64248. if (LSValues && LSValues.y != 0) {
  64249. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  64250. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  64251. this.camera.inertialRadiusOffset -= normalizedLY;
  64252. }
  64253. }
  64254. }
  64255. };
  64256. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  64257. return "ArcRotateCameraGamepadInput";
  64258. };
  64259. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  64260. return "gamepad";
  64261. };
  64262. __decorate([
  64263. BABYLON.serialize()
  64264. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  64265. __decorate([
  64266. BABYLON.serialize()
  64267. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  64268. return ArcRotateCameraGamepadInput;
  64269. }());
  64270. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  64271. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  64272. })(BABYLON || (BABYLON = {}));
  64273. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  64274. var BABYLON;
  64275. (function (BABYLON) {
  64276. var GamepadManager = /** @class */ (function () {
  64277. function GamepadManager(_scene) {
  64278. var _this = this;
  64279. this._scene = _scene;
  64280. this._babylonGamepads = [];
  64281. this._oneGamepadConnected = false;
  64282. this._isMonitoring = false;
  64283. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  64284. if (!BABYLON.Tools.IsWindowObjectExist()) {
  64285. this._gamepadEventSupported = false;
  64286. }
  64287. else {
  64288. this._gamepadEventSupported = 'GamepadEvent' in window;
  64289. this._gamepadSupport = (navigator.getGamepads ||
  64290. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  64291. }
  64292. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  64293. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  64294. for (var i in _this._babylonGamepads) {
  64295. var gamepad = _this._babylonGamepads[i];
  64296. if (gamepad && gamepad._isConnected) {
  64297. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  64298. }
  64299. }
  64300. });
  64301. this._onGamepadConnectedEvent = function (evt) {
  64302. var gamepad = evt.gamepad;
  64303. if (gamepad.index in _this._babylonGamepads) {
  64304. if (_this._babylonGamepads[gamepad.index].isConnected) {
  64305. return;
  64306. }
  64307. }
  64308. var newGamepad;
  64309. if (_this._babylonGamepads[gamepad.index]) {
  64310. newGamepad = _this._babylonGamepads[gamepad.index];
  64311. newGamepad.browserGamepad = gamepad;
  64312. newGamepad._isConnected = true;
  64313. }
  64314. else {
  64315. newGamepad = _this._addNewGamepad(gamepad);
  64316. }
  64317. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  64318. _this._startMonitoringGamepads();
  64319. };
  64320. this._onGamepadDisconnectedEvent = function (evt) {
  64321. var gamepad = evt.gamepad;
  64322. // Remove the gamepad from the list of gamepads to monitor.
  64323. for (var i in _this._babylonGamepads) {
  64324. if (_this._babylonGamepads[i].index === gamepad.index) {
  64325. var disconnectedGamepad = _this._babylonGamepads[i];
  64326. disconnectedGamepad._isConnected = false;
  64327. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  64328. break;
  64329. }
  64330. }
  64331. };
  64332. if (this._gamepadSupport) {
  64333. //first add already-connected gamepads
  64334. this._updateGamepadObjects();
  64335. if (this._babylonGamepads.length) {
  64336. this._startMonitoringGamepads();
  64337. }
  64338. // Checking if the gamepad connected event is supported (like in Firefox)
  64339. if (this._gamepadEventSupported) {
  64340. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  64341. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  64342. }
  64343. else {
  64344. this._startMonitoringGamepads();
  64345. }
  64346. }
  64347. }
  64348. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  64349. get: function () {
  64350. return this._babylonGamepads;
  64351. },
  64352. enumerable: true,
  64353. configurable: true
  64354. });
  64355. GamepadManager.prototype.getGamepadByType = function (type) {
  64356. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  64357. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  64358. var gamepad = _a[_i];
  64359. if (gamepad && gamepad.type === type) {
  64360. return gamepad;
  64361. }
  64362. }
  64363. return null;
  64364. };
  64365. GamepadManager.prototype.dispose = function () {
  64366. if (this._gamepadEventSupported) {
  64367. if (this._onGamepadConnectedEvent) {
  64368. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  64369. }
  64370. if (this._onGamepadDisconnectedEvent) {
  64371. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  64372. }
  64373. this._onGamepadConnectedEvent = null;
  64374. this._onGamepadDisconnectedEvent = null;
  64375. }
  64376. this._babylonGamepads.forEach(function (gamepad) {
  64377. gamepad.dispose();
  64378. });
  64379. this.onGamepadConnectedObservable.clear();
  64380. this.onGamepadDisconnectedObservable.clear();
  64381. this._oneGamepadConnected = false;
  64382. this._stopMonitoringGamepads();
  64383. this._babylonGamepads = [];
  64384. };
  64385. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  64386. if (!this._oneGamepadConnected) {
  64387. this._oneGamepadConnected = true;
  64388. }
  64389. var newGamepad;
  64390. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  64391. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  64392. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  64393. }
  64394. else if (gamepad.pose) {
  64395. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  64396. }
  64397. else {
  64398. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  64399. }
  64400. this._babylonGamepads[newGamepad.index] = newGamepad;
  64401. return newGamepad;
  64402. };
  64403. GamepadManager.prototype._startMonitoringGamepads = function () {
  64404. if (!this._isMonitoring) {
  64405. this._isMonitoring = true;
  64406. //back-comp
  64407. if (!this._scene) {
  64408. this._checkGamepadsStatus();
  64409. }
  64410. }
  64411. };
  64412. GamepadManager.prototype._stopMonitoringGamepads = function () {
  64413. this._isMonitoring = false;
  64414. };
  64415. GamepadManager.prototype._checkGamepadsStatus = function () {
  64416. var _this = this;
  64417. // Hack to be compatible Chrome
  64418. this._updateGamepadObjects();
  64419. for (var i in this._babylonGamepads) {
  64420. var gamepad = this._babylonGamepads[i];
  64421. if (!gamepad || !gamepad.isConnected) {
  64422. continue;
  64423. }
  64424. gamepad.update();
  64425. }
  64426. if (this._isMonitoring && !this._scene) {
  64427. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  64428. }
  64429. };
  64430. // This function is called only on Chrome, which does not properly support
  64431. // connection/disconnection events and forces you to recopy again the gamepad object
  64432. GamepadManager.prototype._updateGamepadObjects = function () {
  64433. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  64434. for (var i = 0; i < gamepads.length; i++) {
  64435. if (gamepads[i]) {
  64436. if (!this._babylonGamepads[gamepads[i].index]) {
  64437. var newGamepad = this._addNewGamepad(gamepads[i]);
  64438. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  64439. }
  64440. else {
  64441. // Forced to copy again this object for Chrome for unknown reason
  64442. this._babylonGamepads[i].browserGamepad = gamepads[i];
  64443. if (!this._babylonGamepads[i].isConnected) {
  64444. this._babylonGamepads[i]._isConnected = true;
  64445. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  64446. }
  64447. }
  64448. }
  64449. }
  64450. };
  64451. return GamepadManager;
  64452. }());
  64453. BABYLON.GamepadManager = GamepadManager;
  64454. })(BABYLON || (BABYLON = {}));
  64455. //# sourceMappingURL=babylon.gamepadManager.js.map
  64456. var BABYLON;
  64457. (function (BABYLON) {
  64458. var StickValues = /** @class */ (function () {
  64459. function StickValues(x, y) {
  64460. this.x = x;
  64461. this.y = y;
  64462. }
  64463. return StickValues;
  64464. }());
  64465. BABYLON.StickValues = StickValues;
  64466. var Gamepad = /** @class */ (function () {
  64467. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  64468. if (leftStickX === void 0) { leftStickX = 0; }
  64469. if (leftStickY === void 0) { leftStickY = 1; }
  64470. if (rightStickX === void 0) { rightStickX = 2; }
  64471. if (rightStickY === void 0) { rightStickY = 3; }
  64472. this.id = id;
  64473. this.index = index;
  64474. this.browserGamepad = browserGamepad;
  64475. this._isConnected = true;
  64476. this._invertLeftStickY = false;
  64477. this.type = Gamepad.GAMEPAD;
  64478. this._leftStickAxisX = leftStickX;
  64479. this._leftStickAxisY = leftStickY;
  64480. this._rightStickAxisX = rightStickX;
  64481. this._rightStickAxisY = rightStickY;
  64482. if (this.browserGamepad.axes.length >= 2) {
  64483. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  64484. }
  64485. if (this.browserGamepad.axes.length >= 4) {
  64486. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  64487. }
  64488. }
  64489. Object.defineProperty(Gamepad.prototype, "isConnected", {
  64490. get: function () {
  64491. return this._isConnected;
  64492. },
  64493. enumerable: true,
  64494. configurable: true
  64495. });
  64496. Gamepad.prototype.onleftstickchanged = function (callback) {
  64497. this._onleftstickchanged = callback;
  64498. };
  64499. Gamepad.prototype.onrightstickchanged = function (callback) {
  64500. this._onrightstickchanged = callback;
  64501. };
  64502. Object.defineProperty(Gamepad.prototype, "leftStick", {
  64503. get: function () {
  64504. return this._leftStick;
  64505. },
  64506. set: function (newValues) {
  64507. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  64508. this._onleftstickchanged(newValues);
  64509. }
  64510. this._leftStick = newValues;
  64511. },
  64512. enumerable: true,
  64513. configurable: true
  64514. });
  64515. Object.defineProperty(Gamepad.prototype, "rightStick", {
  64516. get: function () {
  64517. return this._rightStick;
  64518. },
  64519. set: function (newValues) {
  64520. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  64521. this._onrightstickchanged(newValues);
  64522. }
  64523. this._rightStick = newValues;
  64524. },
  64525. enumerable: true,
  64526. configurable: true
  64527. });
  64528. Gamepad.prototype.update = function () {
  64529. if (this._leftStick) {
  64530. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  64531. if (this._invertLeftStickY) {
  64532. this.leftStick.y *= -1;
  64533. }
  64534. }
  64535. if (this._rightStick) {
  64536. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  64537. }
  64538. };
  64539. Gamepad.prototype.dispose = function () {
  64540. };
  64541. Gamepad.GAMEPAD = 0;
  64542. Gamepad.GENERIC = 1;
  64543. Gamepad.XBOX = 2;
  64544. Gamepad.POSE_ENABLED = 3;
  64545. return Gamepad;
  64546. }());
  64547. BABYLON.Gamepad = Gamepad;
  64548. var GenericPad = /** @class */ (function (_super) {
  64549. __extends(GenericPad, _super);
  64550. function GenericPad(id, index, browserGamepad) {
  64551. var _this = _super.call(this, id, index, browserGamepad) || this;
  64552. _this.onButtonDownObservable = new BABYLON.Observable();
  64553. _this.onButtonUpObservable = new BABYLON.Observable();
  64554. _this.type = Gamepad.GENERIC;
  64555. _this._buttons = new Array(browserGamepad.buttons.length);
  64556. return _this;
  64557. }
  64558. GenericPad.prototype.onbuttondown = function (callback) {
  64559. this._onbuttondown = callback;
  64560. };
  64561. GenericPad.prototype.onbuttonup = function (callback) {
  64562. this._onbuttonup = callback;
  64563. };
  64564. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  64565. if (newValue !== currentValue) {
  64566. if (newValue === 1) {
  64567. if (this._onbuttondown) {
  64568. this._onbuttondown(buttonIndex);
  64569. }
  64570. this.onButtonDownObservable.notifyObservers(buttonIndex);
  64571. }
  64572. if (newValue === 0) {
  64573. if (this._onbuttonup) {
  64574. this._onbuttonup(buttonIndex);
  64575. }
  64576. this.onButtonUpObservable.notifyObservers(buttonIndex);
  64577. }
  64578. }
  64579. return newValue;
  64580. };
  64581. GenericPad.prototype.update = function () {
  64582. _super.prototype.update.call(this);
  64583. for (var index = 0; index < this._buttons.length; index++) {
  64584. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  64585. }
  64586. };
  64587. GenericPad.prototype.dispose = function () {
  64588. _super.prototype.dispose.call(this);
  64589. this.onButtonDownObservable.clear();
  64590. this.onButtonUpObservable.clear();
  64591. };
  64592. return GenericPad;
  64593. }(Gamepad));
  64594. BABYLON.GenericPad = GenericPad;
  64595. })(BABYLON || (BABYLON = {}));
  64596. //# sourceMappingURL=babylon.gamepad.js.map
  64597. var BABYLON;
  64598. (function (BABYLON) {
  64599. var Xbox360Button;
  64600. (function (Xbox360Button) {
  64601. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  64602. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  64603. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  64604. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  64605. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  64606. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  64607. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  64608. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  64609. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  64610. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  64611. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  64612. var Xbox360Dpad;
  64613. (function (Xbox360Dpad) {
  64614. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  64615. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  64616. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  64617. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  64618. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  64619. var Xbox360Pad = /** @class */ (function (_super) {
  64620. __extends(Xbox360Pad, _super);
  64621. function Xbox360Pad(id, index, gamepad, xboxOne) {
  64622. if (xboxOne === void 0) { xboxOne = false; }
  64623. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  64624. _this._leftTrigger = 0;
  64625. _this._rightTrigger = 0;
  64626. _this.onButtonDownObservable = new BABYLON.Observable();
  64627. _this.onButtonUpObservable = new BABYLON.Observable();
  64628. _this.onPadDownObservable = new BABYLON.Observable();
  64629. _this.onPadUpObservable = new BABYLON.Observable();
  64630. _this._buttonA = 0;
  64631. _this._buttonB = 0;
  64632. _this._buttonX = 0;
  64633. _this._buttonY = 0;
  64634. _this._buttonBack = 0;
  64635. _this._buttonStart = 0;
  64636. _this._buttonLB = 0;
  64637. _this._buttonRB = 0;
  64638. _this._buttonLeftStick = 0;
  64639. _this._buttonRightStick = 0;
  64640. _this._dPadUp = 0;
  64641. _this._dPadDown = 0;
  64642. _this._dPadLeft = 0;
  64643. _this._dPadRight = 0;
  64644. _this._isXboxOnePad = false;
  64645. _this.type = BABYLON.Gamepad.XBOX;
  64646. _this._isXboxOnePad = xboxOne;
  64647. return _this;
  64648. }
  64649. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  64650. this._onlefttriggerchanged = callback;
  64651. };
  64652. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  64653. this._onrighttriggerchanged = callback;
  64654. };
  64655. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  64656. get: function () {
  64657. return this._leftTrigger;
  64658. },
  64659. set: function (newValue) {
  64660. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  64661. this._onlefttriggerchanged(newValue);
  64662. }
  64663. this._leftTrigger = newValue;
  64664. },
  64665. enumerable: true,
  64666. configurable: true
  64667. });
  64668. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  64669. get: function () {
  64670. return this._rightTrigger;
  64671. },
  64672. set: function (newValue) {
  64673. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  64674. this._onrighttriggerchanged(newValue);
  64675. }
  64676. this._rightTrigger = newValue;
  64677. },
  64678. enumerable: true,
  64679. configurable: true
  64680. });
  64681. Xbox360Pad.prototype.onbuttondown = function (callback) {
  64682. this._onbuttondown = callback;
  64683. };
  64684. Xbox360Pad.prototype.onbuttonup = function (callback) {
  64685. this._onbuttonup = callback;
  64686. };
  64687. Xbox360Pad.prototype.ondpaddown = function (callback) {
  64688. this._ondpaddown = callback;
  64689. };
  64690. Xbox360Pad.prototype.ondpadup = function (callback) {
  64691. this._ondpadup = callback;
  64692. };
  64693. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  64694. if (newValue !== currentValue) {
  64695. if (newValue === 1) {
  64696. if (this._onbuttondown) {
  64697. this._onbuttondown(buttonType);
  64698. }
  64699. this.onButtonDownObservable.notifyObservers(buttonType);
  64700. }
  64701. if (newValue === 0) {
  64702. if (this._onbuttonup) {
  64703. this._onbuttonup(buttonType);
  64704. }
  64705. this.onButtonUpObservable.notifyObservers(buttonType);
  64706. }
  64707. }
  64708. return newValue;
  64709. };
  64710. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  64711. if (newValue !== currentValue) {
  64712. if (newValue === 1) {
  64713. if (this._ondpaddown) {
  64714. this._ondpaddown(buttonType);
  64715. }
  64716. this.onPadDownObservable.notifyObservers(buttonType);
  64717. }
  64718. if (newValue === 0) {
  64719. if (this._ondpadup) {
  64720. this._ondpadup(buttonType);
  64721. }
  64722. this.onPadUpObservable.notifyObservers(buttonType);
  64723. }
  64724. }
  64725. return newValue;
  64726. };
  64727. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  64728. get: function () {
  64729. return this._buttonA;
  64730. },
  64731. set: function (value) {
  64732. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  64733. },
  64734. enumerable: true,
  64735. configurable: true
  64736. });
  64737. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  64738. get: function () {
  64739. return this._buttonB;
  64740. },
  64741. set: function (value) {
  64742. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  64743. },
  64744. enumerable: true,
  64745. configurable: true
  64746. });
  64747. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  64748. get: function () {
  64749. return this._buttonX;
  64750. },
  64751. set: function (value) {
  64752. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  64753. },
  64754. enumerable: true,
  64755. configurable: true
  64756. });
  64757. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  64758. get: function () {
  64759. return this._buttonY;
  64760. },
  64761. set: function (value) {
  64762. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  64763. },
  64764. enumerable: true,
  64765. configurable: true
  64766. });
  64767. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  64768. get: function () {
  64769. return this._buttonStart;
  64770. },
  64771. set: function (value) {
  64772. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  64773. },
  64774. enumerable: true,
  64775. configurable: true
  64776. });
  64777. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  64778. get: function () {
  64779. return this._buttonBack;
  64780. },
  64781. set: function (value) {
  64782. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  64783. },
  64784. enumerable: true,
  64785. configurable: true
  64786. });
  64787. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  64788. get: function () {
  64789. return this._buttonLB;
  64790. },
  64791. set: function (value) {
  64792. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  64793. },
  64794. enumerable: true,
  64795. configurable: true
  64796. });
  64797. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  64798. get: function () {
  64799. return this._buttonRB;
  64800. },
  64801. set: function (value) {
  64802. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  64803. },
  64804. enumerable: true,
  64805. configurable: true
  64806. });
  64807. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  64808. get: function () {
  64809. return this._buttonLeftStick;
  64810. },
  64811. set: function (value) {
  64812. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  64813. },
  64814. enumerable: true,
  64815. configurable: true
  64816. });
  64817. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  64818. get: function () {
  64819. return this._buttonRightStick;
  64820. },
  64821. set: function (value) {
  64822. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  64823. },
  64824. enumerable: true,
  64825. configurable: true
  64826. });
  64827. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  64828. get: function () {
  64829. return this._dPadUp;
  64830. },
  64831. set: function (value) {
  64832. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  64833. },
  64834. enumerable: true,
  64835. configurable: true
  64836. });
  64837. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  64838. get: function () {
  64839. return this._dPadDown;
  64840. },
  64841. set: function (value) {
  64842. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  64843. },
  64844. enumerable: true,
  64845. configurable: true
  64846. });
  64847. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  64848. get: function () {
  64849. return this._dPadLeft;
  64850. },
  64851. set: function (value) {
  64852. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  64853. },
  64854. enumerable: true,
  64855. configurable: true
  64856. });
  64857. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  64858. get: function () {
  64859. return this._dPadRight;
  64860. },
  64861. set: function (value) {
  64862. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  64863. },
  64864. enumerable: true,
  64865. configurable: true
  64866. });
  64867. Xbox360Pad.prototype.update = function () {
  64868. _super.prototype.update.call(this);
  64869. if (this._isXboxOnePad) {
  64870. this.buttonA = this.browserGamepad.buttons[0].value;
  64871. this.buttonB = this.browserGamepad.buttons[1].value;
  64872. this.buttonX = this.browserGamepad.buttons[2].value;
  64873. this.buttonY = this.browserGamepad.buttons[3].value;
  64874. this.buttonLB = this.browserGamepad.buttons[4].value;
  64875. this.buttonRB = this.browserGamepad.buttons[5].value;
  64876. this.leftTrigger = this.browserGamepad.axes[2];
  64877. this.rightTrigger = this.browserGamepad.axes[5];
  64878. this.buttonBack = this.browserGamepad.buttons[9].value;
  64879. this.buttonStart = this.browserGamepad.buttons[8].value;
  64880. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  64881. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  64882. this.dPadUp = this.browserGamepad.buttons[11].value;
  64883. this.dPadDown = this.browserGamepad.buttons[12].value;
  64884. this.dPadLeft = this.browserGamepad.buttons[13].value;
  64885. this.dPadRight = this.browserGamepad.buttons[14].value;
  64886. }
  64887. else {
  64888. this.buttonA = this.browserGamepad.buttons[0].value;
  64889. this.buttonB = this.browserGamepad.buttons[1].value;
  64890. this.buttonX = this.browserGamepad.buttons[2].value;
  64891. this.buttonY = this.browserGamepad.buttons[3].value;
  64892. this.buttonLB = this.browserGamepad.buttons[4].value;
  64893. this.buttonRB = this.browserGamepad.buttons[5].value;
  64894. this.leftTrigger = this.browserGamepad.buttons[6].value;
  64895. this.rightTrigger = this.browserGamepad.buttons[7].value;
  64896. this.buttonBack = this.browserGamepad.buttons[8].value;
  64897. this.buttonStart = this.browserGamepad.buttons[9].value;
  64898. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  64899. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  64900. this.dPadUp = this.browserGamepad.buttons[12].value;
  64901. this.dPadDown = this.browserGamepad.buttons[13].value;
  64902. this.dPadLeft = this.browserGamepad.buttons[14].value;
  64903. this.dPadRight = this.browserGamepad.buttons[15].value;
  64904. }
  64905. };
  64906. Xbox360Pad.prototype.dispose = function () {
  64907. _super.prototype.dispose.call(this);
  64908. this.onButtonDownObservable.clear();
  64909. this.onButtonUpObservable.clear();
  64910. this.onPadDownObservable.clear();
  64911. this.onPadUpObservable.clear();
  64912. };
  64913. return Xbox360Pad;
  64914. }(BABYLON.Gamepad));
  64915. BABYLON.Xbox360Pad = Xbox360Pad;
  64916. })(BABYLON || (BABYLON = {}));
  64917. //# sourceMappingURL=babylon.xboxGamepad.js.map
  64918. var BABYLON;
  64919. (function (BABYLON) {
  64920. var PoseEnabledControllerType;
  64921. (function (PoseEnabledControllerType) {
  64922. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  64923. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  64924. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  64925. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  64926. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  64927. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  64928. var PoseEnabledControllerHelper = /** @class */ (function () {
  64929. function PoseEnabledControllerHelper() {
  64930. }
  64931. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  64932. // Oculus Touch
  64933. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  64934. return new BABYLON.OculusTouchController(vrGamepad);
  64935. }
  64936. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  64937. return new BABYLON.WindowsMotionController(vrGamepad);
  64938. }
  64939. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  64940. return new BABYLON.ViveController(vrGamepad);
  64941. }
  64942. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  64943. return new BABYLON.GearVRController(vrGamepad);
  64944. }
  64945. else {
  64946. return new BABYLON.GenericController(vrGamepad);
  64947. }
  64948. };
  64949. return PoseEnabledControllerHelper;
  64950. }());
  64951. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  64952. var PoseEnabledController = /** @class */ (function (_super) {
  64953. __extends(PoseEnabledController, _super);
  64954. function PoseEnabledController(browserGamepad) {
  64955. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  64956. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  64957. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  64958. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  64959. // Represents device position and rotation in babylon space
  64960. _this.devicePosition = BABYLON.Vector3.Zero();
  64961. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  64962. _this.deviceScaleFactor = 1;
  64963. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  64964. _this._deviceToWorld = BABYLON.Matrix.Identity();
  64965. _this._workingMatrix = BABYLON.Matrix.Identity();
  64966. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  64967. _this.controllerType = PoseEnabledControllerType.GENERIC;
  64968. _this.position = BABYLON.Vector3.Zero();
  64969. _this.rotationQuaternion = new BABYLON.Quaternion();
  64970. _this._calculatedPosition = BABYLON.Vector3.Zero();
  64971. _this._calculatedRotation = new BABYLON.Quaternion();
  64972. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  64973. return _this;
  64974. }
  64975. PoseEnabledController.prototype.update = function () {
  64976. _super.prototype.update.call(this);
  64977. var pose = this.browserGamepad.pose;
  64978. this.updateFromDevice(pose);
  64979. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  64980. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  64981. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  64982. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  64983. if (this._mesh) {
  64984. this._mesh.position.copyFrom(this.devicePosition);
  64985. if (this._mesh.rotationQuaternion) {
  64986. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  64987. }
  64988. }
  64989. };
  64990. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  64991. if (poseData) {
  64992. this.rawPose = poseData;
  64993. if (poseData.position) {
  64994. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  64995. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  64996. this._deviceRoomPosition.z *= -1;
  64997. }
  64998. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  64999. this._calculatedPosition.addInPlace(this.position);
  65000. }
  65001. var pose = this.rawPose;
  65002. if (poseData.orientation && pose.orientation) {
  65003. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  65004. if (this._mesh) {
  65005. if (this._mesh.getScene().useRightHandedSystem) {
  65006. this._deviceRoomRotationQuaternion.z *= -1;
  65007. this._deviceRoomRotationQuaternion.w *= -1;
  65008. }
  65009. else {
  65010. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  65011. }
  65012. }
  65013. // if the camera is set, rotate to the camera's rotation
  65014. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  65015. }
  65016. }
  65017. };
  65018. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  65019. if (this._mesh) {
  65020. this._mesh.parent = null;
  65021. }
  65022. this._mesh = mesh;
  65023. if (this._poseControlledCamera) {
  65024. this._mesh.parent = this._poseControlledCamera;
  65025. }
  65026. if (!this._mesh.rotationQuaternion) {
  65027. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  65028. }
  65029. };
  65030. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  65031. this._poseControlledCamera = camera;
  65032. if (this._mesh) {
  65033. this._mesh.parent = this._poseControlledCamera;
  65034. }
  65035. };
  65036. PoseEnabledController.prototype.dispose = function () {
  65037. if (this._mesh) {
  65038. this._mesh.dispose();
  65039. }
  65040. this._mesh = null;
  65041. _super.prototype.dispose.call(this);
  65042. };
  65043. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  65044. get: function () {
  65045. return this._mesh;
  65046. },
  65047. enumerable: true,
  65048. configurable: true
  65049. });
  65050. PoseEnabledController.prototype.getForwardRay = function (length) {
  65051. if (length === void 0) { length = 100; }
  65052. if (!this.mesh) {
  65053. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  65054. }
  65055. var m = this.mesh.getWorldMatrix();
  65056. var origin = m.getTranslation();
  65057. var forward = new BABYLON.Vector3(0, 0, -1);
  65058. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  65059. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  65060. return new BABYLON.Ray(origin, direction, length);
  65061. };
  65062. return PoseEnabledController;
  65063. }(BABYLON.Gamepad));
  65064. BABYLON.PoseEnabledController = PoseEnabledController;
  65065. })(BABYLON || (BABYLON = {}));
  65066. //# sourceMappingURL=babylon.poseEnabledController.js.map
  65067. var BABYLON;
  65068. (function (BABYLON) {
  65069. var WebVRController = /** @class */ (function (_super) {
  65070. __extends(WebVRController, _super);
  65071. function WebVRController(vrGamepad) {
  65072. var _this = _super.call(this, vrGamepad) || this;
  65073. // Observables
  65074. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  65075. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  65076. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  65077. _this.onPadStateChangedObservable = new BABYLON.Observable();
  65078. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  65079. _this.pad = { x: 0, y: 0 };
  65080. // avoid GC, store state in a tmp object
  65081. _this._changes = {
  65082. pressChanged: false,
  65083. touchChanged: false,
  65084. valueChanged: false,
  65085. changed: false
  65086. };
  65087. _this._buttons = new Array(vrGamepad.buttons.length);
  65088. _this.hand = vrGamepad.hand;
  65089. return _this;
  65090. }
  65091. WebVRController.prototype.onButtonStateChange = function (callback) {
  65092. this._onButtonStateChange = callback;
  65093. };
  65094. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  65095. get: function () {
  65096. return this._defaultModel;
  65097. },
  65098. enumerable: true,
  65099. configurable: true
  65100. });
  65101. WebVRController.prototype.update = function () {
  65102. _super.prototype.update.call(this);
  65103. for (var index = 0; index < this._buttons.length; index++) {
  65104. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  65105. }
  65106. ;
  65107. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  65108. this.pad.x = this.leftStick.x;
  65109. this.pad.y = this.leftStick.y;
  65110. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  65111. }
  65112. };
  65113. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  65114. if (!newState) {
  65115. newState = {
  65116. pressed: false,
  65117. touched: false,
  65118. value: 0
  65119. };
  65120. }
  65121. if (!currentState) {
  65122. this._buttons[buttonIndex] = {
  65123. pressed: newState.pressed,
  65124. touched: newState.touched,
  65125. value: newState.value
  65126. };
  65127. return;
  65128. }
  65129. this._checkChanges(newState, currentState);
  65130. if (this._changes.changed) {
  65131. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  65132. this.handleButtonChange(buttonIndex, newState, this._changes);
  65133. }
  65134. this._buttons[buttonIndex].pressed = newState.pressed;
  65135. this._buttons[buttonIndex].touched = newState.touched;
  65136. // oculus triggers are never 0, thou not touched.
  65137. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  65138. };
  65139. WebVRController.prototype._checkChanges = function (newState, currentState) {
  65140. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  65141. this._changes.touchChanged = newState.touched !== currentState.touched;
  65142. this._changes.valueChanged = newState.value !== currentState.value;
  65143. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  65144. return this._changes;
  65145. };
  65146. WebVRController.prototype.dispose = function () {
  65147. _super.prototype.dispose.call(this);
  65148. this.onTriggerStateChangedObservable.clear();
  65149. this.onMainButtonStateChangedObservable.clear();
  65150. this.onSecondaryButtonStateChangedObservable.clear();
  65151. this.onPadStateChangedObservable.clear();
  65152. this.onPadValuesChangedObservable.clear();
  65153. };
  65154. return WebVRController;
  65155. }(BABYLON.PoseEnabledController));
  65156. BABYLON.WebVRController = WebVRController;
  65157. })(BABYLON || (BABYLON = {}));
  65158. //# sourceMappingURL=babylon.webVRController.js.map
  65159. var BABYLON;
  65160. (function (BABYLON) {
  65161. var OculusTouchController = /** @class */ (function (_super) {
  65162. __extends(OculusTouchController, _super);
  65163. function OculusTouchController(vrGamepad) {
  65164. var _this = _super.call(this, vrGamepad) || this;
  65165. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  65166. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  65167. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  65168. return _this;
  65169. }
  65170. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65171. var _this = this;
  65172. var meshName;
  65173. // Hand
  65174. if (this.hand === 'left') {
  65175. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  65176. }
  65177. else {
  65178. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  65179. }
  65180. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  65181. /*
  65182. Parent Mesh name: oculus_touch_left
  65183. - body
  65184. - trigger
  65185. - thumbstick
  65186. - grip
  65187. - button_y
  65188. - button_x
  65189. - button_enter
  65190. */
  65191. _this._defaultModel = newMeshes[1];
  65192. _this.attachToMesh(_this._defaultModel);
  65193. if (meshLoaded) {
  65194. meshLoaded(_this._defaultModel);
  65195. }
  65196. });
  65197. };
  65198. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  65199. // helper getters for left and right hand.
  65200. get: function () {
  65201. if (this.hand === 'right') {
  65202. return this.onMainButtonStateChangedObservable;
  65203. }
  65204. else {
  65205. throw new Error('No A button on left hand');
  65206. }
  65207. },
  65208. enumerable: true,
  65209. configurable: true
  65210. });
  65211. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  65212. get: function () {
  65213. if (this.hand === 'right') {
  65214. return this.onSecondaryButtonStateChangedObservable;
  65215. }
  65216. else {
  65217. throw new Error('No B button on left hand');
  65218. }
  65219. },
  65220. enumerable: true,
  65221. configurable: true
  65222. });
  65223. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  65224. get: function () {
  65225. if (this.hand === 'left') {
  65226. return this.onMainButtonStateChangedObservable;
  65227. }
  65228. else {
  65229. throw new Error('No X button on right hand');
  65230. }
  65231. },
  65232. enumerable: true,
  65233. configurable: true
  65234. });
  65235. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  65236. get: function () {
  65237. if (this.hand === 'left') {
  65238. return this.onSecondaryButtonStateChangedObservable;
  65239. }
  65240. else {
  65241. throw new Error('No Y button on right hand');
  65242. }
  65243. },
  65244. enumerable: true,
  65245. configurable: true
  65246. });
  65247. /*
  65248. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  65249. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  65250. 2) secondary trigger (same)
  65251. 3) A (right) X (left), touch, pressed = value
  65252. 4) B / Y
  65253. 5) thumb rest
  65254. */
  65255. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  65256. var notifyObject = state; //{ state: state, changes: changes };
  65257. var triggerDirection = this.hand === 'right' ? -1 : 1;
  65258. switch (buttonIdx) {
  65259. case 0:
  65260. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  65261. return;
  65262. case 1:// index trigger
  65263. if (this._defaultModel) {
  65264. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  65265. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  65266. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  65267. }
  65268. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  65269. return;
  65270. case 2:// secondary trigger
  65271. if (this._defaultModel) {
  65272. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  65273. }
  65274. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  65275. return;
  65276. case 3:
  65277. if (this._defaultModel) {
  65278. if (notifyObject.pressed) {
  65279. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  65280. }
  65281. else {
  65282. (this._defaultModel.getChildren()[1]).position.y = 0;
  65283. }
  65284. }
  65285. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  65286. return;
  65287. case 4:
  65288. if (this._defaultModel) {
  65289. if (notifyObject.pressed) {
  65290. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  65291. }
  65292. else {
  65293. (this._defaultModel.getChildren()[2]).position.y = 0;
  65294. }
  65295. }
  65296. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  65297. return;
  65298. case 5:
  65299. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  65300. return;
  65301. }
  65302. };
  65303. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  65304. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  65305. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  65306. return OculusTouchController;
  65307. }(BABYLON.WebVRController));
  65308. BABYLON.OculusTouchController = OculusTouchController;
  65309. })(BABYLON || (BABYLON = {}));
  65310. //# sourceMappingURL=babylon.oculusTouchController.js.map
  65311. var BABYLON;
  65312. (function (BABYLON) {
  65313. var ViveController = /** @class */ (function (_super) {
  65314. __extends(ViveController, _super);
  65315. function ViveController(vrGamepad) {
  65316. var _this = _super.call(this, vrGamepad) || this;
  65317. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  65318. _this._invertLeftStickY = true;
  65319. return _this;
  65320. }
  65321. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65322. var _this = this;
  65323. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  65324. /*
  65325. Parent Mesh name: ViveWand
  65326. - body
  65327. - r_gripper
  65328. - l_gripper
  65329. - menu_button
  65330. - system_button
  65331. - trackpad
  65332. - trigger
  65333. - LED
  65334. */
  65335. _this._defaultModel = newMeshes[1];
  65336. _this.attachToMesh(_this._defaultModel);
  65337. if (meshLoaded) {
  65338. meshLoaded(_this._defaultModel);
  65339. }
  65340. });
  65341. };
  65342. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  65343. get: function () {
  65344. return this.onMainButtonStateChangedObservable;
  65345. },
  65346. enumerable: true,
  65347. configurable: true
  65348. });
  65349. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  65350. get: function () {
  65351. return this.onMainButtonStateChangedObservable;
  65352. },
  65353. enumerable: true,
  65354. configurable: true
  65355. });
  65356. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  65357. get: function () {
  65358. return this.onSecondaryButtonStateChangedObservable;
  65359. },
  65360. enumerable: true,
  65361. configurable: true
  65362. });
  65363. /**
  65364. * Vive mapping:
  65365. * 0: touchpad
  65366. * 1: trigger
  65367. * 2: left AND right buttons
  65368. * 3: menu button
  65369. */
  65370. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  65371. var notifyObject = state; //{ state: state, changes: changes };
  65372. switch (buttonIdx) {
  65373. case 0:
  65374. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  65375. return;
  65376. case 1:// index trigger
  65377. if (this._defaultModel) {
  65378. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  65379. }
  65380. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  65381. return;
  65382. case 2:// left AND right button
  65383. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  65384. return;
  65385. case 3:
  65386. if (this._defaultModel) {
  65387. if (notifyObject.pressed) {
  65388. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  65389. }
  65390. else {
  65391. (this._defaultModel.getChildren()[2]).position.y = 0;
  65392. }
  65393. }
  65394. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  65395. return;
  65396. }
  65397. };
  65398. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  65399. ViveController.MODEL_FILENAME = 'wand.babylon';
  65400. return ViveController;
  65401. }(BABYLON.WebVRController));
  65402. BABYLON.ViveController = ViveController;
  65403. })(BABYLON || (BABYLON = {}));
  65404. //# sourceMappingURL=babylon.viveController.js.map
  65405. var BABYLON;
  65406. (function (BABYLON) {
  65407. var GenericController = /** @class */ (function (_super) {
  65408. __extends(GenericController, _super);
  65409. function GenericController(vrGamepad) {
  65410. return _super.call(this, vrGamepad) || this;
  65411. }
  65412. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65413. var _this = this;
  65414. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  65415. _this._defaultModel = newMeshes[1];
  65416. _this.attachToMesh(_this._defaultModel);
  65417. if (meshLoaded) {
  65418. meshLoaded(_this._defaultModel);
  65419. }
  65420. });
  65421. };
  65422. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  65423. console.log("Button id: " + buttonIdx + "state: ");
  65424. console.dir(state);
  65425. };
  65426. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65427. GenericController.MODEL_FILENAME = 'generic.babylon';
  65428. return GenericController;
  65429. }(BABYLON.WebVRController));
  65430. BABYLON.GenericController = GenericController;
  65431. })(BABYLON || (BABYLON = {}));
  65432. //# sourceMappingURL=babylon.genericController.js.map
  65433. var BABYLON;
  65434. (function (BABYLON) {
  65435. var LoadedMeshInfo = /** @class */ (function () {
  65436. function LoadedMeshInfo() {
  65437. this.buttonMeshes = {};
  65438. this.axisMeshes = {};
  65439. }
  65440. return LoadedMeshInfo;
  65441. }());
  65442. var WindowsMotionController = /** @class */ (function (_super) {
  65443. __extends(WindowsMotionController, _super);
  65444. function WindowsMotionController(vrGamepad) {
  65445. var _this = _super.call(this, vrGamepad) || this;
  65446. _this._mapping = {
  65447. // Semantic button names
  65448. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  65449. // A mapping of the button name to glTF model node name
  65450. // that should be transformed by button value.
  65451. buttonMeshNames: {
  65452. 'trigger': 'SELECT',
  65453. 'menu': 'MENU',
  65454. 'grip': 'GRASP',
  65455. 'thumbstick': 'THUMBSTICK_PRESS',
  65456. 'trackpad': 'TOUCHPAD_PRESS'
  65457. },
  65458. // This mapping is used to translate from the Motion Controller to Babylon semantics
  65459. buttonObservableNames: {
  65460. 'trigger': 'onTriggerStateChangedObservable',
  65461. 'menu': 'onSecondaryButtonStateChangedObservable',
  65462. 'grip': 'onMainButtonStateChangedObservable',
  65463. 'thumbstick': 'onPadStateChangedObservable',
  65464. 'trackpad': 'onTrackpadChangedObservable'
  65465. },
  65466. // A mapping of the axis name to glTF model node name
  65467. // that should be transformed by axis value.
  65468. // This array mirrors the browserGamepad.axes array, such that
  65469. // the mesh corresponding to axis 0 is in this array index 0.
  65470. axisMeshNames: [
  65471. 'THUMBSTICK_X',
  65472. 'THUMBSTICK_Y',
  65473. 'TOUCHPAD_TOUCH_X',
  65474. 'TOUCHPAD_TOUCH_Y'
  65475. ],
  65476. pointingPoseMeshName: 'POINTING_POSE'
  65477. };
  65478. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  65479. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  65480. _this.trackpad = { x: 0, y: 0 };
  65481. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  65482. _this._loadedMeshInfo = null;
  65483. return _this;
  65484. }
  65485. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  65486. get: function () {
  65487. return this.onTriggerStateChangedObservable;
  65488. },
  65489. enumerable: true,
  65490. configurable: true
  65491. });
  65492. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  65493. get: function () {
  65494. return this.onSecondaryButtonStateChangedObservable;
  65495. },
  65496. enumerable: true,
  65497. configurable: true
  65498. });
  65499. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  65500. get: function () {
  65501. return this.onMainButtonStateChangedObservable;
  65502. },
  65503. enumerable: true,
  65504. configurable: true
  65505. });
  65506. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  65507. get: function () {
  65508. return this.onPadStateChangedObservable;
  65509. },
  65510. enumerable: true,
  65511. configurable: true
  65512. });
  65513. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  65514. get: function () {
  65515. return this.onTrackpadChangedObservable;
  65516. },
  65517. enumerable: true,
  65518. configurable: true
  65519. });
  65520. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  65521. get: function () {
  65522. return this.onTrackpadValuesChangedObservable;
  65523. },
  65524. enumerable: true,
  65525. configurable: true
  65526. });
  65527. /**
  65528. * Called once per frame by the engine.
  65529. */
  65530. WindowsMotionController.prototype.update = function () {
  65531. _super.prototype.update.call(this);
  65532. // Only need to animate axes if there is a loaded mesh
  65533. if (this._loadedMeshInfo) {
  65534. if (this.browserGamepad.axes) {
  65535. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  65536. this.trackpad.x = this.browserGamepad["axes"][2];
  65537. this.trackpad.y = this.browserGamepad["axes"][3];
  65538. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  65539. }
  65540. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  65541. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  65542. }
  65543. }
  65544. }
  65545. };
  65546. /**
  65547. * Called once for each button that changed state since the last frame
  65548. * @param buttonIdx Which button index changed
  65549. * @param state New state of the button
  65550. * @param changes Which properties on the state changed since last frame
  65551. */
  65552. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  65553. var buttonName = this._mapping.buttons[buttonIdx];
  65554. if (!buttonName) {
  65555. return;
  65556. }
  65557. // Only emit events for buttons that we know how to map from index to name
  65558. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  65559. if (observable) {
  65560. observable.notifyObservers(state);
  65561. }
  65562. this.lerpButtonTransform(buttonName, state.value);
  65563. };
  65564. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  65565. // If there is no loaded mesh, there is nothing to transform.
  65566. if (!this._loadedMeshInfo) {
  65567. return;
  65568. }
  65569. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  65570. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  65571. return;
  65572. }
  65573. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  65574. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  65575. };
  65576. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  65577. if (!this._loadedMeshInfo) {
  65578. return;
  65579. }
  65580. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  65581. if (!meshInfo) {
  65582. return;
  65583. }
  65584. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  65585. return;
  65586. }
  65587. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  65588. var lerpValue = axisValue * 0.5 + 0.5;
  65589. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  65590. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  65591. };
  65592. /**
  65593. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  65594. * @param scene scene in which to add meshes
  65595. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  65596. */
  65597. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  65598. var _this = this;
  65599. if (forceDefault === void 0) { forceDefault = false; }
  65600. var path;
  65601. var filename;
  65602. // Checking if GLB loader is present
  65603. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  65604. // Determine the device specific folder based on the ID suffix
  65605. var device = 'default';
  65606. if (this.id && !forceDefault) {
  65607. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  65608. device = ((match && match[0]) || device);
  65609. }
  65610. // Hand
  65611. if (this.hand === 'left') {
  65612. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  65613. }
  65614. else {
  65615. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  65616. }
  65617. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  65618. }
  65619. else {
  65620. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  65621. path = BABYLON.GenericController.MODEL_BASE_URL;
  65622. filename = BABYLON.GenericController.MODEL_FILENAME;
  65623. }
  65624. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  65625. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  65626. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  65627. if (!_this._loadedMeshInfo) {
  65628. return;
  65629. }
  65630. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  65631. _this.attachToMesh(_this._defaultModel);
  65632. if (meshLoaded) {
  65633. meshLoaded(_this._defaultModel);
  65634. }
  65635. }, null, function (scene, message) {
  65636. BABYLON.Tools.Log(message);
  65637. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  65638. if (!forceDefault) {
  65639. _this.initControllerMesh(scene, meshLoaded, true);
  65640. }
  65641. });
  65642. };
  65643. /**
  65644. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  65645. * can be transformed by button presses and axes values, based on this._mapping.
  65646. *
  65647. * @param scene scene in which the meshes exist
  65648. * @param meshes list of meshes that make up the controller model to process
  65649. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  65650. */
  65651. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  65652. var loadedMeshInfo = null;
  65653. // Create a new mesh to contain the glTF hierarchy
  65654. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  65655. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  65656. var childMesh = null;
  65657. for (var i = 0; i < meshes.length; i++) {
  65658. var mesh = meshes[i];
  65659. if (!mesh.parent) {
  65660. // Exclude controller meshes from picking results
  65661. mesh.isPickable = false;
  65662. // Handle root node, attach to the new parentMesh
  65663. childMesh = mesh;
  65664. break;
  65665. }
  65666. }
  65667. if (childMesh) {
  65668. childMesh.setParent(parentMesh);
  65669. // Create our mesh info. Note that this method will always return non-null.
  65670. loadedMeshInfo = this.createMeshInfo(parentMesh);
  65671. }
  65672. else {
  65673. BABYLON.Tools.Warn('Could not find root node in model file.');
  65674. }
  65675. return loadedMeshInfo;
  65676. };
  65677. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  65678. var loadedMeshInfo = new LoadedMeshInfo();
  65679. var i;
  65680. loadedMeshInfo.rootNode = rootNode;
  65681. // Reset the caches
  65682. loadedMeshInfo.buttonMeshes = {};
  65683. loadedMeshInfo.axisMeshes = {};
  65684. // Button Meshes
  65685. for (i = 0; i < this._mapping.buttons.length; i++) {
  65686. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  65687. if (!buttonMeshName) {
  65688. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  65689. continue;
  65690. }
  65691. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  65692. if (!buttonMesh) {
  65693. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  65694. continue;
  65695. }
  65696. var buttonMeshInfo = {
  65697. index: i,
  65698. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  65699. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  65700. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  65701. };
  65702. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  65703. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  65704. }
  65705. else {
  65706. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  65707. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  65708. '(VALUE: ' + !!buttonMeshInfo.value +
  65709. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  65710. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  65711. ')');
  65712. }
  65713. }
  65714. // Axis Meshes
  65715. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  65716. var axisMeshName = this._mapping.axisMeshNames[i];
  65717. if (!axisMeshName) {
  65718. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  65719. continue;
  65720. }
  65721. var axisMesh = getChildByName(rootNode, axisMeshName);
  65722. if (!axisMesh) {
  65723. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  65724. continue;
  65725. }
  65726. var axisMeshInfo = {
  65727. index: i,
  65728. value: getImmediateChildByName(axisMesh, 'VALUE'),
  65729. min: getImmediateChildByName(axisMesh, 'MIN'),
  65730. max: getImmediateChildByName(axisMesh, 'MAX')
  65731. };
  65732. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  65733. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  65734. }
  65735. else {
  65736. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  65737. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  65738. '(VALUE: ' + !!axisMeshInfo.value +
  65739. ', MIN: ' + !!axisMeshInfo.min +
  65740. ', MAX:' + !!axisMeshInfo.max +
  65741. ')');
  65742. }
  65743. }
  65744. // Pointing Ray
  65745. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  65746. if (!loadedMeshInfo.pointingPoseNode) {
  65747. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  65748. }
  65749. return loadedMeshInfo;
  65750. // Look through all children recursively. This will return null if no mesh exists with the given name.
  65751. function getChildByName(node, name) {
  65752. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  65753. }
  65754. // Look through only immediate children. This will return null if no mesh exists with the given name.
  65755. function getImmediateChildByName(node, name) {
  65756. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  65757. }
  65758. };
  65759. WindowsMotionController.prototype.getForwardRay = function (length) {
  65760. if (length === void 0) { length = 100; }
  65761. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  65762. return _super.prototype.getForwardRay.call(this, length);
  65763. }
  65764. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  65765. var origin = m.getTranslation();
  65766. var forward = new BABYLON.Vector3(0, 0, -1);
  65767. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  65768. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  65769. return new BABYLON.Ray(origin, direction, length);
  65770. };
  65771. WindowsMotionController.prototype.dispose = function () {
  65772. _super.prototype.dispose.call(this);
  65773. this.onTrackpadChangedObservable.clear();
  65774. };
  65775. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  65776. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  65777. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  65778. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  65779. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  65780. return WindowsMotionController;
  65781. }(BABYLON.WebVRController));
  65782. BABYLON.WindowsMotionController = WindowsMotionController;
  65783. })(BABYLON || (BABYLON = {}));
  65784. //# sourceMappingURL=babylon.windowsMotionController.js.map
  65785. var BABYLON;
  65786. (function (BABYLON) {
  65787. var GearVRController = /** @class */ (function (_super) {
  65788. __extends(GearVRController, _super);
  65789. function GearVRController(vrGamepad) {
  65790. var _this = _super.call(this, vrGamepad) || this;
  65791. _this._buttonIndexToObservableNameMap = [
  65792. 'onTrackpadChangedObservable',
  65793. 'onTriggerStateChangedObservable' // Trigger
  65794. ];
  65795. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  65796. return _this;
  65797. }
  65798. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65799. var _this = this;
  65800. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  65801. _this._defaultModel = newMeshes[1];
  65802. _this.attachToMesh(_this._defaultModel);
  65803. if (meshLoaded) {
  65804. meshLoaded(_this._defaultModel);
  65805. }
  65806. });
  65807. };
  65808. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  65809. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  65810. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  65811. // Only emit events for buttons that we know how to map from index to observable
  65812. var observable = this[observableName];
  65813. if (observable) {
  65814. observable.notifyObservers(state);
  65815. }
  65816. }
  65817. };
  65818. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65819. GearVRController.MODEL_FILENAME = 'generic.babylon';
  65820. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  65821. return GearVRController;
  65822. }(BABYLON.WebVRController));
  65823. BABYLON.GearVRController = GearVRController;
  65824. })(BABYLON || (BABYLON = {}));
  65825. //# sourceMappingURL=babylon.gearVRController.js.map
  65826. var BABYLON;
  65827. (function (BABYLON) {
  65828. var FollowCamera = /** @class */ (function (_super) {
  65829. __extends(FollowCamera, _super);
  65830. function FollowCamera(name, position, scene, lockedTarget) {
  65831. if (lockedTarget === void 0) { lockedTarget = null; }
  65832. var _this = _super.call(this, name, position, scene) || this;
  65833. _this.radius = 12;
  65834. _this.rotationOffset = 0;
  65835. _this.heightOffset = 4;
  65836. _this.cameraAcceleration = 0.05;
  65837. _this.maxCameraSpeed = 20;
  65838. _this.lockedTarget = lockedTarget;
  65839. return _this;
  65840. }
  65841. FollowCamera.prototype.getRadians = function (degrees) {
  65842. return degrees * Math.PI / 180;
  65843. };
  65844. FollowCamera.prototype.follow = function (cameraTarget) {
  65845. if (!cameraTarget)
  65846. return;
  65847. var yRotation;
  65848. if (cameraTarget.rotationQuaternion) {
  65849. var rotMatrix = new BABYLON.Matrix();
  65850. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  65851. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  65852. }
  65853. else {
  65854. yRotation = cameraTarget.rotation.y;
  65855. }
  65856. var radians = this.getRadians(this.rotationOffset) + yRotation;
  65857. var targetPosition = cameraTarget.getAbsolutePosition();
  65858. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  65859. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  65860. var dx = targetX - this.position.x;
  65861. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  65862. var dz = (targetZ) - this.position.z;
  65863. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  65864. var vy = dy * this.cameraAcceleration;
  65865. var vz = dz * this.cameraAcceleration * 2;
  65866. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  65867. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65868. }
  65869. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  65870. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65871. }
  65872. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  65873. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65874. }
  65875. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  65876. this.setTarget(targetPosition);
  65877. };
  65878. FollowCamera.prototype._checkInputs = function () {
  65879. _super.prototype._checkInputs.call(this);
  65880. if (this.lockedTarget) {
  65881. this.follow(this.lockedTarget);
  65882. }
  65883. };
  65884. FollowCamera.prototype.getClassName = function () {
  65885. return "FollowCamera";
  65886. };
  65887. __decorate([
  65888. BABYLON.serialize()
  65889. ], FollowCamera.prototype, "radius", void 0);
  65890. __decorate([
  65891. BABYLON.serialize()
  65892. ], FollowCamera.prototype, "rotationOffset", void 0);
  65893. __decorate([
  65894. BABYLON.serialize()
  65895. ], FollowCamera.prototype, "heightOffset", void 0);
  65896. __decorate([
  65897. BABYLON.serialize()
  65898. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  65899. __decorate([
  65900. BABYLON.serialize()
  65901. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  65902. __decorate([
  65903. BABYLON.serializeAsMeshReference("lockedTargetId")
  65904. ], FollowCamera.prototype, "lockedTarget", void 0);
  65905. return FollowCamera;
  65906. }(BABYLON.TargetCamera));
  65907. BABYLON.FollowCamera = FollowCamera;
  65908. var ArcFollowCamera = /** @class */ (function (_super) {
  65909. __extends(ArcFollowCamera, _super);
  65910. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  65911. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  65912. _this.alpha = alpha;
  65913. _this.beta = beta;
  65914. _this.radius = radius;
  65915. _this.target = target;
  65916. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  65917. _this.follow();
  65918. return _this;
  65919. }
  65920. ArcFollowCamera.prototype.follow = function () {
  65921. if (!this.target) {
  65922. return;
  65923. }
  65924. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  65925. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  65926. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  65927. var targetPosition = this.target.getAbsolutePosition();
  65928. this.position = targetPosition.add(this._cartesianCoordinates);
  65929. this.setTarget(targetPosition);
  65930. };
  65931. ArcFollowCamera.prototype._checkInputs = function () {
  65932. _super.prototype._checkInputs.call(this);
  65933. this.follow();
  65934. };
  65935. ArcFollowCamera.prototype.getClassName = function () {
  65936. return "ArcFollowCamera";
  65937. };
  65938. return ArcFollowCamera;
  65939. }(BABYLON.TargetCamera));
  65940. BABYLON.ArcFollowCamera = ArcFollowCamera;
  65941. })(BABYLON || (BABYLON = {}));
  65942. //# sourceMappingURL=babylon.followCamera.js.map
  65943. var BABYLON;
  65944. (function (BABYLON) {
  65945. // We're mainly based on the logic defined into the FreeCamera code
  65946. var UniversalCamera = /** @class */ (function (_super) {
  65947. __extends(UniversalCamera, _super);
  65948. //-- end properties for backward compatibility for inputs
  65949. function UniversalCamera(name, position, scene) {
  65950. var _this = _super.call(this, name, position, scene) || this;
  65951. _this.inputs.addGamepad();
  65952. return _this;
  65953. }
  65954. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  65955. //-- Begin properties for backward compatibility for inputs
  65956. get: function () {
  65957. var gamepad = this.inputs.attached["gamepad"];
  65958. if (gamepad)
  65959. return gamepad.gamepadAngularSensibility;
  65960. return 0;
  65961. },
  65962. set: function (value) {
  65963. var gamepad = this.inputs.attached["gamepad"];
  65964. if (gamepad)
  65965. gamepad.gamepadAngularSensibility = value;
  65966. },
  65967. enumerable: true,
  65968. configurable: true
  65969. });
  65970. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  65971. get: function () {
  65972. var gamepad = this.inputs.attached["gamepad"];
  65973. if (gamepad)
  65974. return gamepad.gamepadMoveSensibility;
  65975. return 0;
  65976. },
  65977. set: function (value) {
  65978. var gamepad = this.inputs.attached["gamepad"];
  65979. if (gamepad)
  65980. gamepad.gamepadMoveSensibility = value;
  65981. },
  65982. enumerable: true,
  65983. configurable: true
  65984. });
  65985. UniversalCamera.prototype.getClassName = function () {
  65986. return "UniversalCamera";
  65987. };
  65988. return UniversalCamera;
  65989. }(BABYLON.TouchCamera));
  65990. BABYLON.UniversalCamera = UniversalCamera;
  65991. })(BABYLON || (BABYLON = {}));
  65992. //# sourceMappingURL=babylon.universalCamera.js.map
  65993. var BABYLON;
  65994. (function (BABYLON) {
  65995. // We're mainly based on the logic defined into the FreeCamera code
  65996. var GamepadCamera = /** @class */ (function (_super) {
  65997. __extends(GamepadCamera, _super);
  65998. //-- end properties for backward compatibility for inputs
  65999. function GamepadCamera(name, position, scene) {
  66000. return _super.call(this, name, position, scene) || this;
  66001. }
  66002. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  66003. //-- Begin properties for backward compatibility for inputs
  66004. get: function () {
  66005. var gamepad = this.inputs.attached["gamepad"];
  66006. if (gamepad)
  66007. return gamepad.gamepadAngularSensibility;
  66008. return 0;
  66009. },
  66010. set: function (value) {
  66011. var gamepad = this.inputs.attached["gamepad"];
  66012. if (gamepad)
  66013. gamepad.gamepadAngularSensibility = value;
  66014. },
  66015. enumerable: true,
  66016. configurable: true
  66017. });
  66018. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  66019. get: function () {
  66020. var gamepad = this.inputs.attached["gamepad"];
  66021. if (gamepad)
  66022. return gamepad.gamepadMoveSensibility;
  66023. return 0;
  66024. },
  66025. set: function (value) {
  66026. var gamepad = this.inputs.attached["gamepad"];
  66027. if (gamepad)
  66028. gamepad.gamepadMoveSensibility = value;
  66029. },
  66030. enumerable: true,
  66031. configurable: true
  66032. });
  66033. GamepadCamera.prototype.getClassName = function () {
  66034. return "GamepadCamera";
  66035. };
  66036. return GamepadCamera;
  66037. }(BABYLON.UniversalCamera));
  66038. BABYLON.GamepadCamera = GamepadCamera;
  66039. })(BABYLON || (BABYLON = {}));
  66040. //# sourceMappingURL=babylon.gamepadCamera.js.map
  66041. var BABYLON;
  66042. (function (BABYLON) {
  66043. var PostProcessRenderPipelineManager = /** @class */ (function () {
  66044. function PostProcessRenderPipelineManager() {
  66045. this._renderPipelines = {};
  66046. }
  66047. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  66048. this._renderPipelines[renderPipeline._name] = renderPipeline;
  66049. };
  66050. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  66051. if (unique === void 0) { unique = false; }
  66052. var renderPipeline = this._renderPipelines[renderPipelineName];
  66053. if (!renderPipeline) {
  66054. return;
  66055. }
  66056. renderPipeline._attachCameras(cameras, unique);
  66057. };
  66058. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  66059. var renderPipeline = this._renderPipelines[renderPipelineName];
  66060. if (!renderPipeline) {
  66061. return;
  66062. }
  66063. renderPipeline._detachCameras(cameras);
  66064. };
  66065. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  66066. var renderPipeline = this._renderPipelines[renderPipelineName];
  66067. if (!renderPipeline) {
  66068. return;
  66069. }
  66070. renderPipeline._enableEffect(renderEffectName, cameras);
  66071. };
  66072. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  66073. var renderPipeline = this._renderPipelines[renderPipelineName];
  66074. if (!renderPipeline) {
  66075. return;
  66076. }
  66077. renderPipeline._disableEffect(renderEffectName, cameras);
  66078. };
  66079. PostProcessRenderPipelineManager.prototype.update = function () {
  66080. for (var renderPipelineName in this._renderPipelines) {
  66081. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66082. var pipeline = this._renderPipelines[renderPipelineName];
  66083. if (!pipeline.isSupported) {
  66084. pipeline.dispose();
  66085. delete this._renderPipelines[renderPipelineName];
  66086. }
  66087. else {
  66088. pipeline._update();
  66089. }
  66090. }
  66091. }
  66092. };
  66093. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  66094. for (var renderPipelineName in this._renderPipelines) {
  66095. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66096. var pipeline = this._renderPipelines[renderPipelineName];
  66097. pipeline._rebuild();
  66098. }
  66099. }
  66100. };
  66101. PostProcessRenderPipelineManager.prototype.dispose = function () {
  66102. for (var renderPipelineName in this._renderPipelines) {
  66103. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66104. var pipeline = this._renderPipelines[renderPipelineName];
  66105. pipeline.dispose();
  66106. }
  66107. }
  66108. };
  66109. return PostProcessRenderPipelineManager;
  66110. }());
  66111. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  66112. })(BABYLON || (BABYLON = {}));
  66113. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  66114. var BABYLON;
  66115. (function (BABYLON) {
  66116. /**
  66117. * This represents a set of one or more post processes in Babylon.
  66118. * A post process can be used to apply a shader to a texture after it is rendered.
  66119. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  66120. */
  66121. var PostProcessRenderEffect = /** @class */ (function () {
  66122. /**
  66123. * Instantiates a post process render effect.
  66124. * A post process can be used to apply a shader to a texture after it is rendered.
  66125. * @param engine The engine the effect is tied to
  66126. * @param name The name of the effect
  66127. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  66128. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  66129. */
  66130. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  66131. this._name = name;
  66132. this._singleInstance = singleInstance || true;
  66133. this._getPostProcesses = getPostProcesses;
  66134. this._cameras = {};
  66135. this._indicesForCamera = {};
  66136. this._postProcesses = {};
  66137. }
  66138. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  66139. /**
  66140. * Checks if all the post processes in the effect are supported.
  66141. */
  66142. get: function () {
  66143. for (var index in this._postProcesses) {
  66144. for (var ppIndex in this._postProcesses[index]) {
  66145. if (!this._postProcesses[index][ppIndex].isSupported) {
  66146. return false;
  66147. }
  66148. }
  66149. }
  66150. return true;
  66151. },
  66152. enumerable: true,
  66153. configurable: true
  66154. });
  66155. /**
  66156. * Updates the current state of the effect
  66157. */
  66158. PostProcessRenderEffect.prototype._update = function () {
  66159. };
  66160. /**
  66161. * Attaches the effect on cameras
  66162. * @param cameras The camera to attach to.
  66163. */
  66164. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  66165. var _this = this;
  66166. var cameraKey;
  66167. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66168. if (!cams) {
  66169. return;
  66170. }
  66171. for (var i = 0; i < cams.length; i++) {
  66172. var camera = cams[i];
  66173. var cameraName = camera.name;
  66174. if (this._singleInstance) {
  66175. cameraKey = 0;
  66176. }
  66177. else {
  66178. cameraKey = cameraName;
  66179. }
  66180. if (!this._postProcesses[cameraKey]) {
  66181. var postProcess = this._getPostProcesses();
  66182. if (postProcess) {
  66183. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  66184. }
  66185. }
  66186. if (!this._indicesForCamera[cameraName]) {
  66187. this._indicesForCamera[cameraName] = [];
  66188. }
  66189. this._postProcesses[cameraKey].forEach(function (postProcess) {
  66190. var index = camera.attachPostProcess(postProcess);
  66191. _this._indicesForCamera[cameraName].push(index);
  66192. });
  66193. if (!this._cameras[cameraName]) {
  66194. this._cameras[cameraName] = camera;
  66195. }
  66196. }
  66197. };
  66198. /**
  66199. * Detatches the effect on cameras
  66200. * @param cameras The camera to detatch from.
  66201. */
  66202. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  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. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66211. camera.detachPostProcess(postProcess);
  66212. });
  66213. if (this._cameras[cameraName]) {
  66214. //this._indicesForCamera.splice(index, 1);
  66215. this._cameras[cameraName] = null;
  66216. }
  66217. }
  66218. };
  66219. /**
  66220. * Enables the effect on given cameras
  66221. * @param cameras The camera to enable.
  66222. */
  66223. PostProcessRenderEffect.prototype._enable = function (cameras) {
  66224. var _this = this;
  66225. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66226. if (!cams) {
  66227. return;
  66228. }
  66229. for (var i = 0; i < cams.length; i++) {
  66230. var camera = cams[i];
  66231. var cameraName = camera.name;
  66232. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  66233. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  66234. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66235. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  66236. });
  66237. }
  66238. }
  66239. }
  66240. };
  66241. /**
  66242. * Disables the effect on the given cameras
  66243. * @param cameras The camera to disable.
  66244. */
  66245. PostProcessRenderEffect.prototype._disable = function (cameras) {
  66246. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66247. if (!cams) {
  66248. return;
  66249. }
  66250. for (var i = 0; i < cams.length; i++) {
  66251. var camera = cams[i];
  66252. var cameraName = camera.name;
  66253. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66254. camera.detachPostProcess(postProcess);
  66255. });
  66256. }
  66257. };
  66258. /**
  66259. * Gets a list of the post processes contained in the effect.
  66260. * @param camera The camera to get the post processes on.
  66261. * @returns The list of the post processes in the effect.
  66262. */
  66263. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  66264. if (this._singleInstance) {
  66265. return this._postProcesses[0];
  66266. }
  66267. else {
  66268. if (!camera) {
  66269. return null;
  66270. }
  66271. return this._postProcesses[camera.name];
  66272. }
  66273. };
  66274. return PostProcessRenderEffect;
  66275. }());
  66276. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  66277. })(BABYLON || (BABYLON = {}));
  66278. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  66279. var BABYLON;
  66280. (function (BABYLON) {
  66281. var PostProcessRenderPipeline = /** @class */ (function () {
  66282. function PostProcessRenderPipeline(engine, name) {
  66283. this.engine = engine;
  66284. this._name = name;
  66285. this._renderEffects = {};
  66286. this._renderEffectsForIsolatedPass = new Array();
  66287. this._cameras = [];
  66288. }
  66289. PostProcessRenderPipeline.prototype.getClassName = function () {
  66290. return "PostProcessRenderPipeline";
  66291. };
  66292. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  66293. get: function () {
  66294. for (var renderEffectName in this._renderEffects) {
  66295. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66296. if (!this._renderEffects[renderEffectName].isSupported) {
  66297. return false;
  66298. }
  66299. }
  66300. }
  66301. return true;
  66302. },
  66303. enumerable: true,
  66304. configurable: true
  66305. });
  66306. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  66307. this._renderEffects[renderEffect._name] = renderEffect;
  66308. };
  66309. // private
  66310. PostProcessRenderPipeline.prototype._rebuild = function () {
  66311. };
  66312. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  66313. var renderEffects = this._renderEffects[renderEffectName];
  66314. if (!renderEffects) {
  66315. return;
  66316. }
  66317. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  66318. };
  66319. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  66320. var renderEffects = this._renderEffects[renderEffectName];
  66321. if (!renderEffects) {
  66322. return;
  66323. }
  66324. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  66325. };
  66326. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  66327. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66328. if (!cams) {
  66329. return;
  66330. }
  66331. var indicesToDelete = [];
  66332. var i;
  66333. for (i = 0; i < cams.length; i++) {
  66334. var camera = cams[i];
  66335. var cameraName = camera.name;
  66336. if (this._cameras.indexOf(camera) === -1) {
  66337. this._cameras[cameraName] = camera;
  66338. }
  66339. else if (unique) {
  66340. indicesToDelete.push(i);
  66341. }
  66342. }
  66343. for (i = 0; i < indicesToDelete.length; i++) {
  66344. cameras.splice(indicesToDelete[i], 1);
  66345. }
  66346. for (var renderEffectName in this._renderEffects) {
  66347. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66348. this._renderEffects[renderEffectName]._attachCameras(cams);
  66349. }
  66350. }
  66351. };
  66352. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  66353. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66354. if (!cams) {
  66355. return;
  66356. }
  66357. for (var renderEffectName in this._renderEffects) {
  66358. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66359. this._renderEffects[renderEffectName]._detachCameras(cams);
  66360. }
  66361. }
  66362. for (var i = 0; i < cams.length; i++) {
  66363. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  66364. }
  66365. };
  66366. PostProcessRenderPipeline.prototype._update = function () {
  66367. for (var renderEffectName in this._renderEffects) {
  66368. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66369. this._renderEffects[renderEffectName]._update();
  66370. }
  66371. }
  66372. for (var i = 0; i < this._cameras.length; i++) {
  66373. var cameraName = this._cameras[i].name;
  66374. if (this._renderEffectsForIsolatedPass[cameraName]) {
  66375. this._renderEffectsForIsolatedPass[cameraName]._update();
  66376. }
  66377. }
  66378. };
  66379. PostProcessRenderPipeline.prototype._reset = function () {
  66380. this._renderEffects = {};
  66381. this._renderEffectsForIsolatedPass = new Array();
  66382. };
  66383. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function () {
  66384. // Set samples of the very first post process to 4 to enable native anti-aliasing in browsers that support webGL 2.0 (See: https://github.com/BabylonJS/Babylon.js/issues/3754)
  66385. var effectKeys = Object.keys(this._renderEffects);
  66386. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  66387. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  66388. if (postProcesses) {
  66389. postProcesses[0].samples = 4;
  66390. return true;
  66391. }
  66392. }
  66393. return false;
  66394. };
  66395. PostProcessRenderPipeline.prototype.dispose = function () {
  66396. // Must be implemented by children
  66397. };
  66398. __decorate([
  66399. BABYLON.serialize()
  66400. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  66401. return PostProcessRenderPipeline;
  66402. }());
  66403. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  66404. })(BABYLON || (BABYLON = {}));
  66405. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  66406. var BABYLON;
  66407. (function (BABYLON) {
  66408. /**
  66409. * This represents a depth renderer in Babylon.
  66410. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  66411. */
  66412. var DepthRenderer = /** @class */ (function () {
  66413. /**
  66414. * Instantiates a depth renderer
  66415. * @param scene The scene the renderer belongs to
  66416. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  66417. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  66418. */
  66419. function DepthRenderer(scene, type, camera) {
  66420. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  66421. if (camera === void 0) { camera = null; }
  66422. var _this = this;
  66423. this._scene = scene;
  66424. this._camera = camera;
  66425. var engine = scene.getEngine();
  66426. // Render target
  66427. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  66428. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66429. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66430. this._depthMap.refreshRate = 1;
  66431. this._depthMap.renderParticles = false;
  66432. this._depthMap.renderList = null;
  66433. // Camera to get depth map from to support multiple concurrent cameras
  66434. this._depthMap.activeCamera = this._camera;
  66435. this._depthMap.ignoreCameraViewport = true;
  66436. this._depthMap.useCameraPostProcesses = false;
  66437. // set default depth value to 1.0 (far away)
  66438. this._depthMap.onClearObservable.add(function (engine) {
  66439. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  66440. });
  66441. // Custom render function
  66442. var renderSubMesh = function (subMesh) {
  66443. var mesh = subMesh.getRenderingMesh();
  66444. var scene = _this._scene;
  66445. var engine = scene.getEngine();
  66446. var material = subMesh.getMaterial();
  66447. if (!material) {
  66448. return;
  66449. }
  66450. // Culling and reverse (right handed system)
  66451. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  66452. // Managing instances
  66453. var batch = mesh._getInstancesRenderList(subMesh._id);
  66454. if (batch.mustReturn) {
  66455. return;
  66456. }
  66457. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  66458. var camera = _this._camera || scene.activeCamera;
  66459. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  66460. engine.enableEffect(_this._effect);
  66461. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  66462. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  66463. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  66464. // Alpha test
  66465. if (material && material.needAlphaTesting()) {
  66466. var alphaTexture = material.getAlphaTestTexture();
  66467. if (alphaTexture) {
  66468. _this._effect.setTexture("diffuseSampler", alphaTexture);
  66469. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  66470. }
  66471. }
  66472. // Bones
  66473. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  66474. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  66475. }
  66476. // Draw
  66477. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66478. }
  66479. };
  66480. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66481. var index;
  66482. if (depthOnlySubMeshes.length) {
  66483. engine.setColorWrite(false);
  66484. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66485. renderSubMesh(depthOnlySubMeshes.data[index]);
  66486. }
  66487. engine.setColorWrite(true);
  66488. }
  66489. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66490. renderSubMesh(opaqueSubMeshes.data[index]);
  66491. }
  66492. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66493. renderSubMesh(alphaTestSubMeshes.data[index]);
  66494. }
  66495. };
  66496. }
  66497. /**
  66498. * Creates the depth rendering effect and checks if the effect is ready.
  66499. * @param subMesh The submesh to be used to render the depth map of
  66500. * @param useInstances If multiple world instances should be used
  66501. * @returns if the depth renderer is ready to render the depth map
  66502. */
  66503. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  66504. var material = subMesh.getMaterial();
  66505. if (material.disableDepthWrite) {
  66506. return false;
  66507. }
  66508. var defines = [];
  66509. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66510. var mesh = subMesh.getMesh();
  66511. // Alpha test
  66512. if (material && material.needAlphaTesting()) {
  66513. defines.push("#define ALPHATEST");
  66514. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66515. attribs.push(BABYLON.VertexBuffer.UVKind);
  66516. defines.push("#define UV1");
  66517. }
  66518. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66519. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66520. defines.push("#define UV2");
  66521. }
  66522. }
  66523. // Bones
  66524. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66525. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66526. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66527. if (mesh.numBoneInfluencers > 4) {
  66528. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66529. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66530. }
  66531. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66532. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  66533. }
  66534. else {
  66535. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66536. }
  66537. // Instances
  66538. if (useInstances) {
  66539. defines.push("#define INSTANCES");
  66540. attribs.push("world0");
  66541. attribs.push("world1");
  66542. attribs.push("world2");
  66543. attribs.push("world3");
  66544. }
  66545. // Get correct effect
  66546. var join = defines.join("\n");
  66547. if (this._cachedDefines !== join) {
  66548. this._cachedDefines = join;
  66549. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  66550. }
  66551. return this._effect.isReady();
  66552. };
  66553. /**
  66554. * Gets the texture which the depth map will be written to.
  66555. * @returns The depth map texture
  66556. */
  66557. DepthRenderer.prototype.getDepthMap = function () {
  66558. return this._depthMap;
  66559. };
  66560. /**
  66561. * Disposes of the depth renderer.
  66562. */
  66563. DepthRenderer.prototype.dispose = function () {
  66564. this._depthMap.dispose();
  66565. };
  66566. return DepthRenderer;
  66567. }());
  66568. BABYLON.DepthRenderer = DepthRenderer;
  66569. })(BABYLON || (BABYLON = {}));
  66570. //# sourceMappingURL=babylon.depthRenderer.js.map
  66571. var BABYLON;
  66572. (function (BABYLON) {
  66573. var SSAORenderingPipeline = /** @class */ (function (_super) {
  66574. __extends(SSAORenderingPipeline, _super);
  66575. /**
  66576. * @constructor
  66577. * @param {string} name - The rendering pipeline name
  66578. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66579. * @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 }
  66580. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66581. */
  66582. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  66583. var _this = _super.call(this, scene.getEngine(), name) || this;
  66584. // Members
  66585. /**
  66586. * The PassPostProcess id in the pipeline that contains the original scene color
  66587. * @type {string}
  66588. */
  66589. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  66590. /**
  66591. * The SSAO PostProcess id in the pipeline
  66592. * @type {string}
  66593. */
  66594. _this.SSAORenderEffect = "SSAORenderEffect";
  66595. /**
  66596. * The horizontal blur PostProcess id in the pipeline
  66597. * @type {string}
  66598. */
  66599. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  66600. /**
  66601. * The vertical blur PostProcess id in the pipeline
  66602. * @type {string}
  66603. */
  66604. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  66605. /**
  66606. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  66607. * @type {string}
  66608. */
  66609. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  66610. /**
  66611. * The output strength of the SSAO post-process. Default value is 1.0.
  66612. * @type {number}
  66613. */
  66614. _this.totalStrength = 1.0;
  66615. /**
  66616. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  66617. * @type {number}
  66618. */
  66619. _this.radius = 0.0001;
  66620. /**
  66621. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  66622. * Must not be equal to fallOff and superior to fallOff.
  66623. * Default value is 0.975
  66624. * @type {number}
  66625. */
  66626. _this.area = 0.0075;
  66627. /**
  66628. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  66629. * Must not be equal to area and inferior to area.
  66630. * Default value is 0.0
  66631. * @type {number}
  66632. */
  66633. _this.fallOff = 0.000001;
  66634. /**
  66635. * The base color of the SSAO post-process
  66636. * The final result is "base + ssao" between [0, 1]
  66637. * @type {number}
  66638. */
  66639. _this.base = 0.5;
  66640. _this._firstUpdate = true;
  66641. _this._scene = scene;
  66642. // Set up assets
  66643. _this._createRandomTexture();
  66644. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  66645. var ssaoRatio = ratio.ssaoRatio || ratio;
  66646. var combineRatio = ratio.combineRatio || ratio;
  66647. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  66648. _this._createSSAOPostProcess(ssaoRatio);
  66649. _this._createBlurPostProcess(ssaoRatio);
  66650. _this._createSSAOCombinePostProcess(combineRatio);
  66651. // Set up pipeline
  66652. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  66653. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  66654. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  66655. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  66656. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  66657. // Finish
  66658. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66659. if (cameras)
  66660. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66661. return _this;
  66662. }
  66663. // Public Methods
  66664. /**
  66665. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  66666. */
  66667. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  66668. if (disableDepthRender === void 0) { disableDepthRender = false; }
  66669. for (var i = 0; i < this._scene.cameras.length; i++) {
  66670. var camera = this._scene.cameras[i];
  66671. this._originalColorPostProcess.dispose(camera);
  66672. this._ssaoPostProcess.dispose(camera);
  66673. this._blurHPostProcess.dispose(camera);
  66674. this._blurVPostProcess.dispose(camera);
  66675. this._ssaoCombinePostProcess.dispose(camera);
  66676. }
  66677. this._randomTexture.dispose();
  66678. if (disableDepthRender)
  66679. this._scene.disableDepthRenderer();
  66680. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66681. _super.prototype.dispose.call(this);
  66682. };
  66683. // Private Methods
  66684. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  66685. var _this = this;
  66686. var size = 16;
  66687. 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);
  66688. 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);
  66689. this._blurHPostProcess.onActivateObservable.add(function () {
  66690. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  66691. _this._blurHPostProcess.kernel = size * dw;
  66692. });
  66693. this._blurVPostProcess.onActivateObservable.add(function () {
  66694. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  66695. _this._blurVPostProcess.kernel = size * dw;
  66696. });
  66697. };
  66698. SSAORenderingPipeline.prototype._rebuild = function () {
  66699. this._firstUpdate = true;
  66700. _super.prototype._rebuild.call(this);
  66701. };
  66702. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  66703. var _this = this;
  66704. var numSamples = 16;
  66705. var sampleSphere = [
  66706. 0.5381, 0.1856, -0.4319,
  66707. 0.1379, 0.2486, 0.4430,
  66708. 0.3371, 0.5679, -0.0057,
  66709. -0.6999, -0.0451, -0.0019,
  66710. 0.0689, -0.1598, -0.8547,
  66711. 0.0560, 0.0069, -0.1843,
  66712. -0.0146, 0.1402, 0.0762,
  66713. 0.0100, -0.1924, -0.0344,
  66714. -0.3577, -0.5301, -0.4358,
  66715. -0.3169, 0.1063, 0.0158,
  66716. 0.0103, -0.5869, 0.0046,
  66717. -0.0897, -0.4940, 0.3287,
  66718. 0.7119, -0.0154, -0.0918,
  66719. -0.0533, 0.0596, -0.5411,
  66720. 0.0352, -0.0631, 0.5460,
  66721. -0.4776, 0.2847, -0.0271
  66722. ];
  66723. var samplesFactor = 1.0 / numSamples;
  66724. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  66725. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  66726. "area", "fallOff", "base", "range", "viewport"
  66727. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  66728. this._ssaoPostProcess.onApply = function (effect) {
  66729. if (_this._firstUpdate) {
  66730. effect.setArray3("sampleSphere", sampleSphere);
  66731. effect.setFloat("samplesFactor", samplesFactor);
  66732. effect.setFloat("randTextureTiles", 4.0);
  66733. }
  66734. effect.setFloat("totalStrength", _this.totalStrength);
  66735. effect.setFloat("radius", _this.radius);
  66736. effect.setFloat("area", _this.area);
  66737. effect.setFloat("fallOff", _this.fallOff);
  66738. effect.setFloat("base", _this.base);
  66739. effect.setTexture("textureSampler", _this._depthTexture);
  66740. effect.setTexture("randomSampler", _this._randomTexture);
  66741. };
  66742. };
  66743. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  66744. var _this = this;
  66745. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66746. this._ssaoCombinePostProcess.onApply = function (effect) {
  66747. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  66748. };
  66749. };
  66750. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  66751. var size = 512;
  66752. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  66753. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66754. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66755. var context = this._randomTexture.getContext();
  66756. var rand = function (min, max) {
  66757. return Math.random() * (max - min) + min;
  66758. };
  66759. var randVector = BABYLON.Vector3.Zero();
  66760. for (var x = 0; x < size; x++) {
  66761. for (var y = 0; y < size; y++) {
  66762. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  66763. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  66764. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  66765. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  66766. context.fillRect(x, y, 1, 1);
  66767. }
  66768. }
  66769. this._randomTexture.update(false);
  66770. };
  66771. __decorate([
  66772. BABYLON.serialize()
  66773. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  66774. __decorate([
  66775. BABYLON.serialize()
  66776. ], SSAORenderingPipeline.prototype, "radius", void 0);
  66777. __decorate([
  66778. BABYLON.serialize()
  66779. ], SSAORenderingPipeline.prototype, "area", void 0);
  66780. __decorate([
  66781. BABYLON.serialize()
  66782. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  66783. __decorate([
  66784. BABYLON.serialize()
  66785. ], SSAORenderingPipeline.prototype, "base", void 0);
  66786. return SSAORenderingPipeline;
  66787. }(BABYLON.PostProcessRenderPipeline));
  66788. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  66789. })(BABYLON || (BABYLON = {}));
  66790. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  66791. var BABYLON;
  66792. (function (BABYLON) {
  66793. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  66794. __extends(SSAO2RenderingPipeline, _super);
  66795. /**
  66796. * @constructor
  66797. * @param {string} name - The rendering pipeline name
  66798. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66799. * @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 }
  66800. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66801. */
  66802. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  66803. var _this = _super.call(this, scene.getEngine(), name) || this;
  66804. // Members
  66805. /**
  66806. * The PassPostProcess id in the pipeline that contains the original scene color
  66807. * @type {string}
  66808. */
  66809. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  66810. /**
  66811. * The SSAO PostProcess id in the pipeline
  66812. * @type {string}
  66813. */
  66814. _this.SSAORenderEffect = "SSAORenderEffect";
  66815. /**
  66816. * The horizontal blur PostProcess id in the pipeline
  66817. * @type {string}
  66818. */
  66819. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  66820. /**
  66821. * The vertical blur PostProcess id in the pipeline
  66822. * @type {string}
  66823. */
  66824. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  66825. /**
  66826. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  66827. * @type {string}
  66828. */
  66829. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  66830. /**
  66831. * The output strength of the SSAO post-process. Default value is 1.0.
  66832. * @type {number}
  66833. */
  66834. _this.totalStrength = 1.0;
  66835. /**
  66836. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  66837. * @type {number}
  66838. */
  66839. _this.maxZ = 100.0;
  66840. /**
  66841. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  66842. * @type {number}
  66843. */
  66844. _this.minZAspect = 0.2;
  66845. /**
  66846. * Number of samples used for the SSAO calculations. Default value is 8
  66847. * @type {number}
  66848. */
  66849. _this._samples = 8;
  66850. /**
  66851. * Are we using bilateral blur ?
  66852. * @type {boolean}
  66853. */
  66854. _this._expensiveBlur = true;
  66855. /**
  66856. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  66857. * @type {number}
  66858. */
  66859. _this.radius = 2.0;
  66860. /**
  66861. * The base color of the SSAO post-process
  66862. * The final result is "base + ssao" between [0, 1]
  66863. * @type {number}
  66864. */
  66865. _this.base = 0.1;
  66866. _this._firstUpdate = true;
  66867. _this._scene = scene;
  66868. if (!_this.isSupported) {
  66869. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  66870. return _this;
  66871. }
  66872. var ssaoRatio = ratio.ssaoRatio || ratio;
  66873. var blurRatio = ratio.blurRatio || ratio;
  66874. // Set up assets
  66875. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  66876. _this._createRandomTexture();
  66877. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  66878. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  66879. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  66880. _this._createSSAOPostProcess(1.0);
  66881. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  66882. _this._createSSAOCombinePostProcess(blurRatio);
  66883. // Set up pipeline
  66884. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  66885. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  66886. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  66887. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  66888. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  66889. // Finish
  66890. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66891. if (cameras)
  66892. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66893. return _this;
  66894. }
  66895. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  66896. get: function () {
  66897. return this._samples;
  66898. },
  66899. set: function (n) {
  66900. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  66901. this._samples = n;
  66902. this._sampleSphere = this._generateHemisphere();
  66903. this._firstUpdate = true;
  66904. },
  66905. enumerable: true,
  66906. configurable: true
  66907. });
  66908. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  66909. get: function () {
  66910. return this._expensiveBlur;
  66911. },
  66912. set: function (b) {
  66913. 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"]);
  66914. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  66915. this._expensiveBlur = b;
  66916. this._firstUpdate = true;
  66917. },
  66918. enumerable: true,
  66919. configurable: true
  66920. });
  66921. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  66922. /**
  66923. * Support test.
  66924. * @type {boolean}
  66925. */
  66926. get: function () {
  66927. var engine = BABYLON.Engine.LastCreatedEngine;
  66928. if (!engine) {
  66929. return false;
  66930. }
  66931. return engine.getCaps().drawBuffersExtension;
  66932. },
  66933. enumerable: true,
  66934. configurable: true
  66935. });
  66936. // Public Methods
  66937. /**
  66938. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  66939. */
  66940. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  66941. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  66942. for (var i = 0; i < this._scene.cameras.length; i++) {
  66943. var camera = this._scene.cameras[i];
  66944. this._originalColorPostProcess.dispose(camera);
  66945. this._ssaoPostProcess.dispose(camera);
  66946. this._blurHPostProcess.dispose(camera);
  66947. this._blurVPostProcess.dispose(camera);
  66948. this._ssaoCombinePostProcess.dispose(camera);
  66949. }
  66950. this._randomTexture.dispose();
  66951. if (disableGeometryBufferRenderer)
  66952. this._scene.disableGeometryBufferRenderer();
  66953. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66954. _super.prototype.dispose.call(this);
  66955. };
  66956. // Private Methods
  66957. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  66958. var _this = this;
  66959. this._samplerOffsets = [];
  66960. var expensive = this.expensiveBlur;
  66961. for (var i = -8; i < 8; i++) {
  66962. this._samplerOffsets.push(i * 2 + 0.5);
  66963. }
  66964. 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");
  66965. this._blurHPostProcess.onApply = function (effect) {
  66966. if (!_this._scene.activeCamera) {
  66967. return;
  66968. }
  66969. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  66970. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66971. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66972. effect.setFloat("radius", _this.radius);
  66973. effect.setTexture("depthSampler", _this._depthTexture);
  66974. if (_this._firstUpdate) {
  66975. effect.setArray("samplerOffsets", _this._samplerOffsets);
  66976. }
  66977. };
  66978. 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");
  66979. this._blurVPostProcess.onApply = function (effect) {
  66980. if (!_this._scene.activeCamera) {
  66981. return;
  66982. }
  66983. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  66984. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66985. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66986. effect.setFloat("radius", _this.radius);
  66987. effect.setTexture("depthSampler", _this._depthTexture);
  66988. if (_this._firstUpdate) {
  66989. effect.setArray("samplerOffsets", _this._samplerOffsets);
  66990. _this._firstUpdate = false;
  66991. }
  66992. };
  66993. };
  66994. SSAO2RenderingPipeline.prototype._rebuild = function () {
  66995. this._firstUpdate = true;
  66996. _super.prototype._rebuild.call(this);
  66997. };
  66998. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  66999. var numSamples = this.samples;
  67000. var result = [];
  67001. var vector, scale;
  67002. var rand = function (min, max) {
  67003. return Math.random() * (max - min) + min;
  67004. };
  67005. var i = 0;
  67006. while (i < numSamples) {
  67007. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  67008. vector.normalize();
  67009. scale = i / numSamples;
  67010. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  67011. vector.scaleInPlace(scale);
  67012. result.push(vector.x, vector.y, vector.z);
  67013. i++;
  67014. }
  67015. return result;
  67016. };
  67017. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  67018. var _this = this;
  67019. var numSamples = this.samples;
  67020. this._sampleSphere = this._generateHemisphere();
  67021. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  67022. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  67023. "base", "range", "projection", "near", "far", "texelSize",
  67024. "xViewport", "yViewport", "maxZ", "minZAspect"
  67025. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  67026. this._ssaoPostProcess.onApply = function (effect) {
  67027. if (_this._firstUpdate) {
  67028. effect.setArray3("sampleSphere", _this._sampleSphere);
  67029. effect.setFloat("randTextureTiles", 4.0);
  67030. }
  67031. if (!_this._scene.activeCamera) {
  67032. return;
  67033. }
  67034. effect.setFloat("samplesFactor", 1 / _this.samples);
  67035. effect.setFloat("totalStrength", _this.totalStrength);
  67036. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  67037. effect.setFloat("radius", _this.radius);
  67038. effect.setFloat("maxZ", _this.maxZ);
  67039. effect.setFloat("minZAspect", _this.minZAspect);
  67040. effect.setFloat("base", _this.base);
  67041. effect.setFloat("near", _this._scene.activeCamera.minZ);
  67042. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  67043. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  67044. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  67045. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  67046. effect.setTexture("textureSampler", _this._depthTexture);
  67047. effect.setTexture("normalSampler", _this._normalTexture);
  67048. effect.setTexture("randomSampler", _this._randomTexture);
  67049. };
  67050. };
  67051. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  67052. var _this = this;
  67053. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67054. this._ssaoCombinePostProcess.onApply = function (effect) {
  67055. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  67056. };
  67057. };
  67058. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  67059. var size = 512;
  67060. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67061. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67062. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67063. var context = this._randomTexture.getContext();
  67064. var rand = function (min, max) {
  67065. return Math.random() * (max - min) + min;
  67066. };
  67067. var randVector = BABYLON.Vector3.Zero();
  67068. for (var x = 0; x < size; x++) {
  67069. for (var y = 0; y < size; y++) {
  67070. randVector.x = rand(0.0, 1.0);
  67071. randVector.y = rand(0.0, 1.0);
  67072. randVector.z = 0.0;
  67073. randVector.normalize();
  67074. randVector.scaleInPlace(255);
  67075. randVector.x = Math.floor(randVector.x);
  67076. randVector.y = Math.floor(randVector.y);
  67077. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  67078. context.fillRect(x, y, 1, 1);
  67079. }
  67080. }
  67081. this._randomTexture.update(false);
  67082. };
  67083. __decorate([
  67084. BABYLON.serialize()
  67085. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  67086. __decorate([
  67087. BABYLON.serialize()
  67088. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  67089. __decorate([
  67090. BABYLON.serialize()
  67091. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  67092. __decorate([
  67093. BABYLON.serialize("samples")
  67094. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  67095. __decorate([
  67096. BABYLON.serialize("expensiveBlur")
  67097. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  67098. __decorate([
  67099. BABYLON.serialize()
  67100. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  67101. __decorate([
  67102. BABYLON.serialize()
  67103. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  67104. return SSAO2RenderingPipeline;
  67105. }(BABYLON.PostProcessRenderPipeline));
  67106. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  67107. })(BABYLON || (BABYLON = {}));
  67108. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  67109. // BABYLON.JS Chromatic Aberration GLSL Shader
  67110. // Author: Olivier Guyot
  67111. // Separates very slightly R, G and B colors on the edges of the screen
  67112. // Inspired by Francois Tarlier & Martins Upitis
  67113. var BABYLON;
  67114. (function (BABYLON) {
  67115. var LensRenderingPipeline = /** @class */ (function (_super) {
  67116. __extends(LensRenderingPipeline, _super);
  67117. /**
  67118. * @constructor
  67119. *
  67120. * Effect parameters are as follow:
  67121. * {
  67122. * chromatic_aberration: number; // from 0 to x (1 for realism)
  67123. * edge_blur: number; // from 0 to x (1 for realism)
  67124. * distortion: number; // from 0 to x (1 for realism)
  67125. * grain_amount: number; // from 0 to 1
  67126. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  67127. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  67128. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  67129. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  67130. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  67131. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  67132. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  67133. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  67134. * }
  67135. * Note: if an effect parameter is unset, effect is disabled
  67136. *
  67137. * @param {string} name - The rendering pipeline name
  67138. * @param {object} parameters - An object containing all parameters (see above)
  67139. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67140. * @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)
  67141. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67142. */
  67143. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  67144. if (ratio === void 0) { ratio = 1.0; }
  67145. var _this = _super.call(this, scene.getEngine(), name) || this;
  67146. // Lens effects can be of the following:
  67147. // - chromatic aberration (slight shift of RGB colors)
  67148. // - blur on the edge of the lens
  67149. // - lens distortion
  67150. // - depth-of-field blur & highlights enhancing
  67151. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  67152. // - grain effect (noise or custom texture)
  67153. // Two additional texture samplers are needed:
  67154. // - depth map (for depth-of-field)
  67155. // - grain texture
  67156. /**
  67157. * The chromatic aberration PostProcess id in the pipeline
  67158. * @type {string}
  67159. */
  67160. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  67161. /**
  67162. * The highlights enhancing PostProcess id in the pipeline
  67163. * @type {string}
  67164. */
  67165. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  67166. /**
  67167. * The depth-of-field PostProcess id in the pipeline
  67168. * @type {string}
  67169. */
  67170. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  67171. _this._scene = scene;
  67172. // Fetch texture samplers
  67173. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  67174. if (parameters.grain_texture) {
  67175. _this._grainTexture = parameters.grain_texture;
  67176. }
  67177. else {
  67178. _this._createGrainTexture();
  67179. }
  67180. // save parameters
  67181. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  67182. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  67183. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  67184. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  67185. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  67186. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  67187. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  67188. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  67189. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  67190. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  67191. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  67192. // Create effects
  67193. _this._createChromaticAberrationPostProcess(ratio);
  67194. _this._createHighlightsPostProcess(ratio);
  67195. _this._createDepthOfFieldPostProcess(ratio / 4);
  67196. // Set up pipeline
  67197. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  67198. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  67199. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  67200. if (_this._highlightsGain === -1) {
  67201. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  67202. }
  67203. // Finish
  67204. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67205. if (cameras) {
  67206. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  67207. }
  67208. return _this;
  67209. }
  67210. // public methods (self explanatory)
  67211. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  67212. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  67213. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  67214. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  67215. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  67216. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  67217. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  67218. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  67219. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  67220. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  67221. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  67222. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  67223. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  67224. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  67225. };
  67226. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  67227. this._highlightsPostProcess.updateEffect();
  67228. };
  67229. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  67230. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  67231. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  67232. this._highlightsGain = amount;
  67233. };
  67234. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  67235. if (this._highlightsGain === -1) {
  67236. this._highlightsGain = 1.0;
  67237. }
  67238. this._highlightsThreshold = amount;
  67239. };
  67240. LensRenderingPipeline.prototype.disableHighlights = function () {
  67241. this._highlightsGain = -1;
  67242. };
  67243. /**
  67244. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  67245. */
  67246. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  67247. if (disableDepthRender === void 0) { disableDepthRender = false; }
  67248. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  67249. this._chromaticAberrationPostProcess = null;
  67250. this._highlightsPostProcess = null;
  67251. this._depthOfFieldPostProcess = null;
  67252. this._grainTexture.dispose();
  67253. if (disableDepthRender)
  67254. this._scene.disableDepthRenderer();
  67255. };
  67256. // colors shifting and distortion
  67257. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  67258. var _this = this;
  67259. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  67260. [], // samplers
  67261. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67262. this._chromaticAberrationPostProcess.onApply = function (effect) {
  67263. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  67264. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67265. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67266. };
  67267. };
  67268. // highlights enhancing
  67269. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  67270. var _this = this;
  67271. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  67272. [], // samplers
  67273. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  67274. this._highlightsPostProcess.onApply = function (effect) {
  67275. effect.setFloat('gain', _this._highlightsGain);
  67276. effect.setFloat('threshold', _this._highlightsThreshold);
  67277. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  67278. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67279. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67280. };
  67281. };
  67282. // colors shifting and distortion
  67283. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  67284. var _this = this;
  67285. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  67286. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  67287. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  67288. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67289. this._depthOfFieldPostProcess.onApply = function (effect) {
  67290. effect.setTexture("depthSampler", _this._depthTexture);
  67291. effect.setTexture("grainSampler", _this._grainTexture);
  67292. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  67293. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  67294. effect.setFloat('grain_amount', _this._grainAmount);
  67295. effect.setBool('blur_noise', _this._blurNoise);
  67296. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67297. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67298. effect.setFloat('distortion', _this._distortion);
  67299. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  67300. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  67301. effect.setFloat('aperture', _this._dofAperture);
  67302. effect.setFloat('darken', _this._dofDarken);
  67303. effect.setFloat('edge_blur', _this._edgeBlur);
  67304. effect.setBool('highlights', (_this._highlightsGain !== -1));
  67305. if (_this._scene.activeCamera) {
  67306. effect.setFloat('near', _this._scene.activeCamera.minZ);
  67307. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  67308. }
  67309. };
  67310. };
  67311. // creates a black and white random noise texture, 512x512
  67312. LensRenderingPipeline.prototype._createGrainTexture = function () {
  67313. var size = 512;
  67314. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67315. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67316. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67317. var context = this._grainTexture.getContext();
  67318. var rand = function (min, max) {
  67319. return Math.random() * (max - min) + min;
  67320. };
  67321. var value;
  67322. for (var x = 0; x < size; x++) {
  67323. for (var y = 0; y < size; y++) {
  67324. value = Math.floor(rand(0.42, 0.58) * 255);
  67325. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  67326. context.fillRect(x, y, 1, 1);
  67327. }
  67328. }
  67329. this._grainTexture.update(false);
  67330. };
  67331. return LensRenderingPipeline;
  67332. }(BABYLON.PostProcessRenderPipeline));
  67333. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  67334. })(BABYLON || (BABYLON = {}));
  67335. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  67336. var BABYLON;
  67337. (function (BABYLON) {
  67338. var StandardRenderingPipeline = /** @class */ (function (_super) {
  67339. __extends(StandardRenderingPipeline, _super);
  67340. /**
  67341. * @constructor
  67342. * @param {string} name - The rendering pipeline name
  67343. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67344. * @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)
  67345. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  67346. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67347. */
  67348. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  67349. if (originalPostProcess === void 0) { originalPostProcess = null; }
  67350. var _this = _super.call(this, scene.getEngine(), name) || this;
  67351. _this.downSampleX4PostProcess = null;
  67352. _this.brightPassPostProcess = null;
  67353. _this.blurHPostProcesses = [];
  67354. _this.blurVPostProcesses = [];
  67355. _this.textureAdderPostProcess = null;
  67356. _this.volumetricLightPostProcess = null;
  67357. _this.volumetricLightSmoothXPostProcess = null;
  67358. _this.volumetricLightSmoothYPostProcess = null;
  67359. _this.volumetricLightMergePostProces = null;
  67360. _this.volumetricLightFinalPostProcess = null;
  67361. _this.luminancePostProcess = null;
  67362. _this.luminanceDownSamplePostProcesses = [];
  67363. _this.hdrPostProcess = null;
  67364. _this.textureAdderFinalPostProcess = null;
  67365. _this.lensFlareFinalPostProcess = null;
  67366. _this.hdrFinalPostProcess = null;
  67367. _this.lensFlarePostProcess = null;
  67368. _this.lensFlareComposePostProcess = null;
  67369. _this.motionBlurPostProcess = null;
  67370. _this.depthOfFieldPostProcess = null;
  67371. // Values
  67372. _this.brightThreshold = 1.0;
  67373. _this.blurWidth = 512.0;
  67374. _this.horizontalBlur = false;
  67375. _this.exposure = 1.0;
  67376. _this.lensTexture = null;
  67377. _this.volumetricLightCoefficient = 0.2;
  67378. _this.volumetricLightPower = 4.0;
  67379. _this.volumetricLightBlurScale = 64.0;
  67380. _this.sourceLight = null;
  67381. _this.hdrMinimumLuminance = 1.0;
  67382. _this.hdrDecreaseRate = 0.5;
  67383. _this.hdrIncreaseRate = 0.5;
  67384. _this.lensColorTexture = null;
  67385. _this.lensFlareStrength = 20.0;
  67386. _this.lensFlareGhostDispersal = 1.4;
  67387. _this.lensFlareHaloWidth = 0.7;
  67388. _this.lensFlareDistortionStrength = 16.0;
  67389. _this.lensStarTexture = null;
  67390. _this.lensFlareDirtTexture = null;
  67391. _this.depthOfFieldDistance = 10.0;
  67392. _this.depthOfFieldBlurWidth = 64.0;
  67393. _this.motionStrength = 1.0;
  67394. // IAnimatable
  67395. _this.animations = [];
  67396. _this._currentDepthOfFieldSource = null;
  67397. _this._hdrCurrentLuminance = 1.0;
  67398. // Getters and setters
  67399. _this._bloomEnabled = true;
  67400. _this._depthOfFieldEnabled = false;
  67401. _this._vlsEnabled = false;
  67402. _this._lensFlareEnabled = false;
  67403. _this._hdrEnabled = false;
  67404. _this._motionBlurEnabled = false;
  67405. _this._motionBlurSamples = 64.0;
  67406. _this._volumetricLightStepsCount = 50.0;
  67407. _this._cameras = cameras || [];
  67408. // Initialize
  67409. _this._scene = scene;
  67410. _this._basePostProcess = originalPostProcess;
  67411. _this._ratio = ratio;
  67412. // Misc
  67413. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67414. // Finish
  67415. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67416. _this._buildPipeline();
  67417. return _this;
  67418. }
  67419. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  67420. get: function () {
  67421. return this._bloomEnabled;
  67422. },
  67423. set: function (enabled) {
  67424. if (this._bloomEnabled === enabled) {
  67425. return;
  67426. }
  67427. this._bloomEnabled = enabled;
  67428. this._buildPipeline();
  67429. },
  67430. enumerable: true,
  67431. configurable: true
  67432. });
  67433. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  67434. get: function () {
  67435. return this._depthOfFieldEnabled;
  67436. },
  67437. set: function (enabled) {
  67438. if (this._depthOfFieldEnabled === enabled) {
  67439. return;
  67440. }
  67441. this._depthOfFieldEnabled = enabled;
  67442. this._buildPipeline();
  67443. },
  67444. enumerable: true,
  67445. configurable: true
  67446. });
  67447. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  67448. get: function () {
  67449. return this._lensFlareEnabled;
  67450. },
  67451. set: function (enabled) {
  67452. if (this._lensFlareEnabled === enabled) {
  67453. return;
  67454. }
  67455. this._lensFlareEnabled = enabled;
  67456. this._buildPipeline();
  67457. },
  67458. enumerable: true,
  67459. configurable: true
  67460. });
  67461. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  67462. get: function () {
  67463. return this._hdrEnabled;
  67464. },
  67465. set: function (enabled) {
  67466. if (this._hdrEnabled === enabled) {
  67467. return;
  67468. }
  67469. this._hdrEnabled = enabled;
  67470. this._buildPipeline();
  67471. },
  67472. enumerable: true,
  67473. configurable: true
  67474. });
  67475. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  67476. get: function () {
  67477. return this._vlsEnabled;
  67478. },
  67479. set: function (enabled) {
  67480. if (this._vlsEnabled === enabled) {
  67481. return;
  67482. }
  67483. if (enabled) {
  67484. var geometry = this._scene.enableGeometryBufferRenderer();
  67485. if (!geometry) {
  67486. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  67487. return;
  67488. }
  67489. }
  67490. this._vlsEnabled = enabled;
  67491. this._buildPipeline();
  67492. },
  67493. enumerable: true,
  67494. configurable: true
  67495. });
  67496. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  67497. get: function () {
  67498. return this._motionBlurEnabled;
  67499. },
  67500. set: function (enabled) {
  67501. if (this._motionBlurEnabled === enabled) {
  67502. return;
  67503. }
  67504. this._motionBlurEnabled = enabled;
  67505. this._buildPipeline();
  67506. },
  67507. enumerable: true,
  67508. configurable: true
  67509. });
  67510. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  67511. get: function () {
  67512. return this._volumetricLightStepsCount;
  67513. },
  67514. set: function (count) {
  67515. if (this.volumetricLightPostProcess) {
  67516. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  67517. }
  67518. this._volumetricLightStepsCount = count;
  67519. },
  67520. enumerable: true,
  67521. configurable: true
  67522. });
  67523. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  67524. get: function () {
  67525. return this._motionBlurSamples;
  67526. },
  67527. set: function (samples) {
  67528. if (this.motionBlurPostProcess) {
  67529. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  67530. }
  67531. this._motionBlurSamples = samples;
  67532. },
  67533. enumerable: true,
  67534. configurable: true
  67535. });
  67536. StandardRenderingPipeline.prototype._buildPipeline = function () {
  67537. var _this = this;
  67538. var ratio = this._ratio;
  67539. var scene = this._scene;
  67540. this._disposePostProcesses();
  67541. this._reset();
  67542. // Create pass post-process
  67543. if (!this._basePostProcess) {
  67544. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  67545. this.originalPostProcess.onApply = function (effect) {
  67546. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  67547. };
  67548. }
  67549. else {
  67550. this.originalPostProcess = this._basePostProcess;
  67551. }
  67552. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  67553. this._currentDepthOfFieldSource = this.originalPostProcess;
  67554. if (this._vlsEnabled) {
  67555. // Create volumetric light
  67556. this._createVolumetricLightPostProcess(scene, ratio);
  67557. // Create volumetric light final post-process
  67558. 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);
  67559. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  67560. }
  67561. if (this._bloomEnabled) {
  67562. // Create down sample X4 post-process
  67563. this._createDownSampleX4PostProcess(scene, ratio / 2);
  67564. // Create bright pass post-process
  67565. this._createBrightPassPostProcess(scene, ratio / 2);
  67566. // Create gaussian blur post-processes (down sampling blurs)
  67567. this._createBlurPostProcesses(scene, ratio / 4, 1);
  67568. // Create texture adder post-process
  67569. this._createTextureAdderPostProcess(scene, ratio);
  67570. // Create depth-of-field source post-process
  67571. 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);
  67572. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  67573. }
  67574. if (this._lensFlareEnabled) {
  67575. // Create lens flare post-process
  67576. this._createLensFlarePostProcess(scene, ratio);
  67577. // Create depth-of-field source post-process post lens-flare and disable it now
  67578. 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);
  67579. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  67580. }
  67581. if (this._hdrEnabled) {
  67582. // Create luminance
  67583. this._createLuminancePostProcesses(scene, this._floatTextureType);
  67584. // Create HDR
  67585. this._createHdrPostProcess(scene, ratio);
  67586. // Create depth-of-field source post-process post hdr and disable it now
  67587. 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);
  67588. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  67589. }
  67590. if (this._depthOfFieldEnabled) {
  67591. // Create gaussian blur used by depth-of-field
  67592. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  67593. // Create depth-of-field post-process
  67594. this._createDepthOfFieldPostProcess(scene, ratio);
  67595. }
  67596. if (this._motionBlurEnabled) {
  67597. // Create motion blur post-process
  67598. this._createMotionBlurPostProcess(scene, ratio);
  67599. }
  67600. if (this._cameras !== null) {
  67601. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  67602. }
  67603. };
  67604. // Down Sample X4 Post-Processs
  67605. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  67606. var _this = this;
  67607. var downSampleX4Offsets = new Array(32);
  67608. 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);
  67609. this.downSampleX4PostProcess.onApply = function (effect) {
  67610. var id = 0;
  67611. var width = _this.downSampleX4PostProcess.width;
  67612. var height = _this.downSampleX4PostProcess.height;
  67613. for (var i = -2; i < 2; i++) {
  67614. for (var j = -2; j < 2; j++) {
  67615. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  67616. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  67617. id += 2;
  67618. }
  67619. }
  67620. effect.setArray2("dsOffsets", downSampleX4Offsets);
  67621. };
  67622. // Add to pipeline
  67623. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  67624. };
  67625. // Brightpass Post-Process
  67626. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  67627. var _this = this;
  67628. var brightOffsets = new Array(8);
  67629. 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);
  67630. this.brightPassPostProcess.onApply = function (effect) {
  67631. var sU = (1.0 / _this.brightPassPostProcess.width);
  67632. var sV = (1.0 / _this.brightPassPostProcess.height);
  67633. brightOffsets[0] = -0.5 * sU;
  67634. brightOffsets[1] = 0.5 * sV;
  67635. brightOffsets[2] = 0.5 * sU;
  67636. brightOffsets[3] = 0.5 * sV;
  67637. brightOffsets[4] = -0.5 * sU;
  67638. brightOffsets[5] = -0.5 * sV;
  67639. brightOffsets[6] = 0.5 * sU;
  67640. brightOffsets[7] = -0.5 * sV;
  67641. effect.setArray2("dsOffsets", brightOffsets);
  67642. effect.setFloat("brightThreshold", _this.brightThreshold);
  67643. };
  67644. // Add to pipeline
  67645. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  67646. };
  67647. // Create blur H&V post-processes
  67648. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  67649. var _this = this;
  67650. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  67651. var engine = scene.getEngine();
  67652. 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);
  67653. 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);
  67654. blurX.onActivateObservable.add(function () {
  67655. var dw = blurX.width / engine.getRenderWidth();
  67656. blurX.kernel = _this[blurWidthKey] * dw;
  67657. });
  67658. blurY.onActivateObservable.add(function () {
  67659. var dw = blurY.height / engine.getRenderHeight();
  67660. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  67661. });
  67662. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  67663. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  67664. this.blurHPostProcesses.push(blurX);
  67665. this.blurVPostProcesses.push(blurY);
  67666. };
  67667. // Create texture adder post-process
  67668. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  67669. var _this = this;
  67670. 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);
  67671. this.textureAdderPostProcess.onApply = function (effect) {
  67672. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  67673. effect.setTexture("lensSampler", _this.lensTexture);
  67674. effect.setFloat("exposure", _this.exposure);
  67675. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  67676. };
  67677. // Add to pipeline
  67678. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  67679. };
  67680. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  67681. var _this = this;
  67682. var geometryRenderer = scene.enableGeometryBufferRenderer();
  67683. geometryRenderer.enablePosition = true;
  67684. var geometry = geometryRenderer.getGBuffer();
  67685. // Base post-process
  67686. 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));
  67687. var depthValues = BABYLON.Vector2.Zero();
  67688. this.volumetricLightPostProcess.onApply = function (effect) {
  67689. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  67690. var generator = _this.sourceLight.getShadowGenerator();
  67691. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  67692. effect.setTexture("positionSampler", geometry.textures[2]);
  67693. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  67694. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  67695. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  67696. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  67697. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  67698. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  67699. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  67700. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  67701. effect.setVector2("depthValues", depthValues);
  67702. }
  67703. };
  67704. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  67705. // Smooth
  67706. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  67707. // Merge
  67708. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  67709. this.volumetricLightMergePostProces.onApply = function (effect) {
  67710. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  67711. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  67712. };
  67713. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  67714. };
  67715. // Create luminance
  67716. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  67717. var _this = this;
  67718. // Create luminance
  67719. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  67720. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  67721. var offsets = [];
  67722. this.luminancePostProcess.onApply = function (effect) {
  67723. var sU = (1.0 / _this.luminancePostProcess.width);
  67724. var sV = (1.0 / _this.luminancePostProcess.height);
  67725. offsets[0] = -0.5 * sU;
  67726. offsets[1] = 0.5 * sV;
  67727. offsets[2] = 0.5 * sU;
  67728. offsets[3] = 0.5 * sV;
  67729. offsets[4] = -0.5 * sU;
  67730. offsets[5] = -0.5 * sV;
  67731. offsets[6] = 0.5 * sU;
  67732. offsets[7] = -0.5 * sV;
  67733. effect.setArray2("lumOffsets", offsets);
  67734. };
  67735. // Add to pipeline
  67736. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  67737. // Create down sample luminance
  67738. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  67739. var size = Math.pow(3, i);
  67740. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  67741. if (i === 0) {
  67742. defines += "#define FINAL_DOWN_SAMPLER";
  67743. }
  67744. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  67745. this.luminanceDownSamplePostProcesses.push(postProcess);
  67746. }
  67747. // Create callbacks and add effects
  67748. var lastLuminance = this.luminancePostProcess;
  67749. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  67750. var downSampleOffsets = new Array(18);
  67751. pp.onApply = function (effect) {
  67752. if (!lastLuminance) {
  67753. return;
  67754. }
  67755. var id = 0;
  67756. for (var x = -1; x < 2; x++) {
  67757. for (var y = -1; y < 2; y++) {
  67758. downSampleOffsets[id] = x / lastLuminance.width;
  67759. downSampleOffsets[id + 1] = y / lastLuminance.height;
  67760. id += 2;
  67761. }
  67762. }
  67763. effect.setArray2("dsOffsets", downSampleOffsets);
  67764. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  67765. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  67766. lastLuminance = _this.luminancePostProcess;
  67767. }
  67768. else {
  67769. lastLuminance = pp;
  67770. }
  67771. };
  67772. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  67773. pp.onAfterRender = function (effect) {
  67774. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  67775. 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);
  67776. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  67777. };
  67778. }
  67779. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  67780. });
  67781. };
  67782. // Create HDR post-process
  67783. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  67784. var _this = this;
  67785. 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);
  67786. var outputLiminance = 1;
  67787. var time = 0;
  67788. var lastTime = 0;
  67789. this.hdrPostProcess.onApply = function (effect) {
  67790. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  67791. time += scene.getEngine().getDeltaTime();
  67792. if (outputLiminance < 0) {
  67793. outputLiminance = _this._hdrCurrentLuminance;
  67794. }
  67795. else {
  67796. var dt = (lastTime - time) / 1000.0;
  67797. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  67798. outputLiminance += _this.hdrDecreaseRate * dt;
  67799. }
  67800. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  67801. outputLiminance -= _this.hdrIncreaseRate * dt;
  67802. }
  67803. else {
  67804. outputLiminance = _this._hdrCurrentLuminance;
  67805. }
  67806. }
  67807. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  67808. effect.setFloat("averageLuminance", outputLiminance);
  67809. lastTime = time;
  67810. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  67811. };
  67812. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  67813. };
  67814. // Create lens flare post-process
  67815. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  67816. var _this = this;
  67817. 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);
  67818. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  67819. this._createBlurPostProcesses(scene, ratio / 4, 2);
  67820. 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);
  67821. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  67822. var resolution = new BABYLON.Vector2(0, 0);
  67823. // Lens flare
  67824. this.lensFlarePostProcess.onApply = function (effect) {
  67825. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  67826. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  67827. effect.setFloat("strength", _this.lensFlareStrength);
  67828. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  67829. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  67830. // Shift
  67831. resolution.x = _this.lensFlarePostProcess.width;
  67832. resolution.y = _this.lensFlarePostProcess.height;
  67833. effect.setVector2("resolution", resolution);
  67834. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  67835. };
  67836. // Compose
  67837. 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);
  67838. 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);
  67839. this.lensFlareComposePostProcess.onApply = function (effect) {
  67840. if (!_this._scene.activeCamera) {
  67841. return;
  67842. }
  67843. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  67844. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  67845. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  67846. // Lens start rotation matrix
  67847. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  67848. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  67849. 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));
  67850. camRot *= 4.0;
  67851. 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);
  67852. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  67853. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  67854. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  67855. };
  67856. };
  67857. // Create depth-of-field post-process
  67858. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  67859. var _this = this;
  67860. 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);
  67861. this.depthOfFieldPostProcess.onApply = function (effect) {
  67862. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  67863. effect.setTexture("depthSampler", _this._getDepthTexture());
  67864. effect.setFloat("distance", _this.depthOfFieldDistance);
  67865. };
  67866. // Add to pipeline
  67867. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  67868. };
  67869. // Create motion blur post-process
  67870. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  67871. var _this = this;
  67872. 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);
  67873. var motionScale = 0;
  67874. var prevViewProjection = BABYLON.Matrix.Identity();
  67875. var invViewProjection = BABYLON.Matrix.Identity();
  67876. var viewProjection = BABYLON.Matrix.Identity();
  67877. var screenSize = BABYLON.Vector2.Zero();
  67878. this.motionBlurPostProcess.onApply = function (effect) {
  67879. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  67880. viewProjection.invertToRef(invViewProjection);
  67881. effect.setMatrix("inverseViewProjection", invViewProjection);
  67882. effect.setMatrix("prevViewProjection", prevViewProjection);
  67883. prevViewProjection = viewProjection;
  67884. screenSize.x = _this.motionBlurPostProcess.width;
  67885. screenSize.y = _this.motionBlurPostProcess.height;
  67886. effect.setVector2("screenSize", screenSize);
  67887. motionScale = scene.getEngine().getFps() / 60.0;
  67888. effect.setFloat("motionScale", motionScale);
  67889. effect.setFloat("motionStrength", _this.motionStrength);
  67890. effect.setTexture("depthSampler", _this._getDepthTexture());
  67891. };
  67892. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  67893. };
  67894. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  67895. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  67896. var renderer = this._scene.enableGeometryBufferRenderer();
  67897. return renderer.getGBuffer().textures[0];
  67898. }
  67899. return this._scene.enableDepthRenderer().getDepthMap();
  67900. };
  67901. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  67902. for (var i = 0; i < this._cameras.length; i++) {
  67903. var camera = this._cameras[i];
  67904. if (this.originalPostProcess) {
  67905. this.originalPostProcess.dispose(camera);
  67906. }
  67907. if (this.downSampleX4PostProcess) {
  67908. this.downSampleX4PostProcess.dispose(camera);
  67909. }
  67910. if (this.brightPassPostProcess) {
  67911. this.brightPassPostProcess.dispose(camera);
  67912. }
  67913. if (this.textureAdderPostProcess) {
  67914. this.textureAdderPostProcess.dispose(camera);
  67915. }
  67916. if (this.textureAdderFinalPostProcess) {
  67917. this.textureAdderFinalPostProcess.dispose(camera);
  67918. }
  67919. if (this.volumetricLightPostProcess) {
  67920. this.volumetricLightPostProcess.dispose(camera);
  67921. }
  67922. if (this.volumetricLightSmoothXPostProcess) {
  67923. this.volumetricLightSmoothXPostProcess.dispose(camera);
  67924. }
  67925. if (this.volumetricLightSmoothYPostProcess) {
  67926. this.volumetricLightSmoothYPostProcess.dispose(camera);
  67927. }
  67928. if (this.volumetricLightMergePostProces) {
  67929. this.volumetricLightMergePostProces.dispose(camera);
  67930. }
  67931. if (this.volumetricLightFinalPostProcess) {
  67932. this.volumetricLightFinalPostProcess.dispose(camera);
  67933. }
  67934. if (this.lensFlarePostProcess) {
  67935. this.lensFlarePostProcess.dispose(camera);
  67936. }
  67937. if (this.lensFlareComposePostProcess) {
  67938. this.lensFlareComposePostProcess.dispose(camera);
  67939. }
  67940. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  67941. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  67942. }
  67943. if (this.luminancePostProcess) {
  67944. this.luminancePostProcess.dispose(camera);
  67945. }
  67946. if (this.hdrPostProcess) {
  67947. this.hdrPostProcess.dispose(camera);
  67948. }
  67949. if (this.hdrFinalPostProcess) {
  67950. this.hdrFinalPostProcess.dispose(camera);
  67951. }
  67952. if (this.depthOfFieldPostProcess) {
  67953. this.depthOfFieldPostProcess.dispose(camera);
  67954. }
  67955. if (this.motionBlurPostProcess) {
  67956. this.motionBlurPostProcess.dispose(camera);
  67957. }
  67958. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  67959. this.blurHPostProcesses[j].dispose(camera);
  67960. }
  67961. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  67962. this.blurVPostProcesses[j].dispose(camera);
  67963. }
  67964. }
  67965. this.originalPostProcess = null;
  67966. this.downSampleX4PostProcess = null;
  67967. this.brightPassPostProcess = null;
  67968. this.textureAdderPostProcess = null;
  67969. this.textureAdderFinalPostProcess = null;
  67970. this.volumetricLightPostProcess = null;
  67971. this.volumetricLightSmoothXPostProcess = null;
  67972. this.volumetricLightSmoothYPostProcess = null;
  67973. this.volumetricLightMergePostProces = null;
  67974. this.volumetricLightFinalPostProcess = null;
  67975. this.lensFlarePostProcess = null;
  67976. this.lensFlareComposePostProcess = null;
  67977. this.luminancePostProcess = null;
  67978. this.hdrPostProcess = null;
  67979. this.hdrFinalPostProcess = null;
  67980. this.depthOfFieldPostProcess = null;
  67981. this.motionBlurPostProcess = null;
  67982. this.luminanceDownSamplePostProcesses = [];
  67983. this.blurHPostProcesses = [];
  67984. this.blurVPostProcesses = [];
  67985. };
  67986. // Dispose
  67987. StandardRenderingPipeline.prototype.dispose = function () {
  67988. this._disposePostProcesses();
  67989. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  67990. _super.prototype.dispose.call(this);
  67991. };
  67992. // Serialize rendering pipeline
  67993. StandardRenderingPipeline.prototype.serialize = function () {
  67994. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  67995. serializationObject.customType = "StandardRenderingPipeline";
  67996. return serializationObject;
  67997. };
  67998. /**
  67999. * Static members
  68000. */
  68001. // Parse serialized pipeline
  68002. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  68003. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  68004. };
  68005. // Luminance steps
  68006. StandardRenderingPipeline.LuminanceSteps = 6;
  68007. __decorate([
  68008. BABYLON.serialize()
  68009. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  68010. __decorate([
  68011. BABYLON.serialize()
  68012. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  68013. __decorate([
  68014. BABYLON.serialize()
  68015. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  68016. __decorate([
  68017. BABYLON.serialize()
  68018. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  68019. __decorate([
  68020. BABYLON.serializeAsTexture("lensTexture")
  68021. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  68022. __decorate([
  68023. BABYLON.serialize()
  68024. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  68025. __decorate([
  68026. BABYLON.serialize()
  68027. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  68028. __decorate([
  68029. BABYLON.serialize()
  68030. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  68031. __decorate([
  68032. BABYLON.serialize()
  68033. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  68034. __decorate([
  68035. BABYLON.serialize()
  68036. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  68037. __decorate([
  68038. BABYLON.serialize()
  68039. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  68040. __decorate([
  68041. BABYLON.serializeAsTexture("lensColorTexture")
  68042. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  68043. __decorate([
  68044. BABYLON.serialize()
  68045. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  68046. __decorate([
  68047. BABYLON.serialize()
  68048. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  68049. __decorate([
  68050. BABYLON.serialize()
  68051. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  68052. __decorate([
  68053. BABYLON.serialize()
  68054. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  68055. __decorate([
  68056. BABYLON.serializeAsTexture("lensStarTexture")
  68057. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  68058. __decorate([
  68059. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  68060. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  68061. __decorate([
  68062. BABYLON.serialize()
  68063. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  68064. __decorate([
  68065. BABYLON.serialize()
  68066. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  68067. __decorate([
  68068. BABYLON.serialize()
  68069. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  68070. __decorate([
  68071. BABYLON.serialize()
  68072. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  68073. __decorate([
  68074. BABYLON.serialize()
  68075. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  68076. __decorate([
  68077. BABYLON.serialize()
  68078. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  68079. __decorate([
  68080. BABYLON.serialize()
  68081. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  68082. __decorate([
  68083. BABYLON.serialize()
  68084. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  68085. __decorate([
  68086. BABYLON.serialize()
  68087. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  68088. __decorate([
  68089. BABYLON.serialize()
  68090. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  68091. __decorate([
  68092. BABYLON.serialize()
  68093. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  68094. __decorate([
  68095. BABYLON.serialize()
  68096. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  68097. return StandardRenderingPipeline;
  68098. }(BABYLON.PostProcessRenderPipeline));
  68099. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  68100. })(BABYLON || (BABYLON = {}));
  68101. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  68102. var BABYLON;
  68103. (function (BABYLON) {
  68104. var FxaaPostProcess = /** @class */ (function (_super) {
  68105. __extends(FxaaPostProcess, _super);
  68106. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  68107. if (camera === void 0) { camera = null; }
  68108. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68109. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  68110. _this.onApplyObservable.add(function (effect) {
  68111. var texelSize = _this.texelSize;
  68112. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  68113. });
  68114. return _this;
  68115. }
  68116. return FxaaPostProcess;
  68117. }(BABYLON.PostProcess));
  68118. BABYLON.FxaaPostProcess = FxaaPostProcess;
  68119. })(BABYLON || (BABYLON = {}));
  68120. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  68121. var BABYLON;
  68122. (function (BABYLON) {
  68123. /**
  68124. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  68125. */
  68126. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  68127. __extends(CircleOfConfusionPostProcess, _super);
  68128. /**
  68129. * Creates a new instance of @see CircleOfConfusionPostProcess
  68130. * @param name The name of the effect.
  68131. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  68132. * @param options The required width/height ratio to downsize to before computing the render pass.
  68133. * @param camera The camera to apply the render pass to.
  68134. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68135. * @param engine The engine which the post process will be applied. (default: current engine)
  68136. * @param reusable If the post process can be reused on the same frame. (default: false)
  68137. * @param textureType Type of textures used when performing the post process. (default: 0)
  68138. */
  68139. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType) {
  68140. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68141. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  68142. /**
  68143. * 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.
  68144. */
  68145. _this.lensSize = 50;
  68146. /**
  68147. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  68148. */
  68149. _this.fStop = 1.4;
  68150. /**
  68151. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  68152. */
  68153. _this.focusDistance = 2000;
  68154. /**
  68155. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  68156. */
  68157. _this.focalLength = 50;
  68158. _this.onApplyObservable.add(function (effect) {
  68159. effect.setTexture("depthSampler", depthTexture);
  68160. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  68161. var aperture = _this.lensSize / _this.fStop;
  68162. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  68163. effect.setFloat('focusDistance', _this.focusDistance);
  68164. effect.setFloat('cocPrecalculation', cocPrecalculation);
  68165. effect.setFloat2('cameraMinMaxZ', depthTexture.activeCamera.minZ, depthTexture.activeCamera.maxZ);
  68166. });
  68167. return _this;
  68168. }
  68169. return CircleOfConfusionPostProcess;
  68170. }(BABYLON.PostProcess));
  68171. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  68172. })(BABYLON || (BABYLON = {}));
  68173. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  68174. var BABYLON;
  68175. (function (BABYLON) {
  68176. /**
  68177. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  68178. */
  68179. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  68180. __extends(DepthOfFieldMergePostProcess, _super);
  68181. /**
  68182. * Creates a new instance of @see CircleOfConfusionPostProcess
  68183. * @param name The name of the effect.
  68184. * @param original The non-blurred image to be modified
  68185. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  68186. * @param blurSteps Incrimental bluring post processes.
  68187. * @param options The required width/height ratio to downsize to before computing the render pass.
  68188. * @param camera The camera to apply the render pass to.
  68189. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68190. * @param engine The engine which the post process will be applied. (default: current engine)
  68191. * @param reusable If the post process can be reused on the same frame. (default: false)
  68192. * @param textureType Type of textures used when performing the post process. (default: 0)
  68193. */
  68194. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType) {
  68195. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68196. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, "#define BLUR_LEVEL " + blurSteps.length + "\n", textureType) || this;
  68197. _this.onApplyObservable.add(function (effect) {
  68198. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  68199. effect.setTextureFromPostProcess("originalSampler", original);
  68200. blurSteps.forEach(function (step, index) {
  68201. effect.setTextureFromPostProcess("blurStep" + (index + 1), step);
  68202. });
  68203. });
  68204. return _this;
  68205. }
  68206. return DepthOfFieldMergePostProcess;
  68207. }(BABYLON.PostProcess));
  68208. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  68209. })(BABYLON || (BABYLON = {}));
  68210. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  68211. var BABYLON;
  68212. (function (BABYLON) {
  68213. /**
  68214. * Specifies the level of max blur that should be applied when using the depth of field effect
  68215. */
  68216. var DepthOfFieldEffectBlurLevel;
  68217. (function (DepthOfFieldEffectBlurLevel) {
  68218. /**
  68219. * Subtle blur
  68220. */
  68221. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  68222. /**
  68223. * Medium blur
  68224. */
  68225. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  68226. /**
  68227. * Large blur
  68228. */
  68229. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  68230. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  68231. ;
  68232. /**
  68233. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  68234. */
  68235. var DepthOfFieldEffect = /** @class */ (function (_super) {
  68236. __extends(DepthOfFieldEffect, _super);
  68237. /**
  68238. * Creates a new instance of @see DepthOfFieldEffect
  68239. * @param scene The scene the effect belongs to.
  68240. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  68241. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  68242. */
  68243. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType) {
  68244. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  68245. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  68246. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  68247. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  68248. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  68249. // Capture circle of confusion texture
  68250. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  68251. _this._depthOfFieldPass.autoClear = false;
  68252. // 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)
  68253. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  68254. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  68255. _this._depthOfFieldBlurY = [];
  68256. _this._depthOfFieldBlurX = [];
  68257. var blurCount = 1;
  68258. var kernelSize = 15;
  68259. switch (blurLevel) {
  68260. case DepthOfFieldEffectBlurLevel.High: {
  68261. blurCount = 3;
  68262. kernelSize = 51;
  68263. break;
  68264. }
  68265. case DepthOfFieldEffectBlurLevel.Medium: {
  68266. blurCount = 2;
  68267. kernelSize = 31;
  68268. break;
  68269. }
  68270. default: {
  68271. kernelSize = 15;
  68272. blurCount = 1;
  68273. break;
  68274. }
  68275. }
  68276. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  68277. for (var i = 0; i < blurCount; i++) {
  68278. 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);
  68279. blurY.autoClear = false;
  68280. 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);
  68281. blurX.autoClear = false;
  68282. _this._depthOfFieldBlurY.push(blurY);
  68283. _this._depthOfFieldBlurX.push(blurX);
  68284. }
  68285. // Merge blurred images with original image based on circleOfConfusion
  68286. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY.slice(1), 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  68287. _this._depthOfFieldMerge.autoClear = false;
  68288. // Set all post processes on the effect.
  68289. var effects = [_this._circleOfConfusion, _this._depthOfFieldPass];
  68290. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  68291. effects.push(_this._depthOfFieldBlurY[i]);
  68292. effects.push(_this._depthOfFieldBlurX[i]);
  68293. }
  68294. effects.push(_this._depthOfFieldMerge);
  68295. return effects;
  68296. }, true) || this;
  68297. return _this;
  68298. }
  68299. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  68300. get: function () {
  68301. return this._circleOfConfusion.focalLength;
  68302. },
  68303. /**
  68304. * The focal the length of the camera used in the effect
  68305. */
  68306. set: function (value) {
  68307. this._circleOfConfusion.focalLength = value;
  68308. },
  68309. enumerable: true,
  68310. configurable: true
  68311. });
  68312. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  68313. get: function () {
  68314. return this._circleOfConfusion.fStop;
  68315. },
  68316. /**
  68317. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  68318. */
  68319. set: function (value) {
  68320. this._circleOfConfusion.fStop = value;
  68321. },
  68322. enumerable: true,
  68323. configurable: true
  68324. });
  68325. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  68326. get: function () {
  68327. return this._circleOfConfusion.focusDistance;
  68328. },
  68329. /**
  68330. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  68331. */
  68332. set: function (value) {
  68333. this._circleOfConfusion.focusDistance = value;
  68334. },
  68335. enumerable: true,
  68336. configurable: true
  68337. });
  68338. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  68339. get: function () {
  68340. return this._circleOfConfusion.lensSize;
  68341. },
  68342. /**
  68343. * 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.
  68344. */
  68345. set: function (value) {
  68346. this._circleOfConfusion.lensSize = value;
  68347. },
  68348. enumerable: true,
  68349. configurable: true
  68350. });
  68351. /**
  68352. * Disposes each of the internal effects for a given camera.
  68353. * @param camera The camera to dispose the effect on.
  68354. */
  68355. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  68356. this._depthOfFieldPass.dispose(camera);
  68357. this._circleOfConfusion.dispose(camera);
  68358. this._depthOfFieldBlurX.forEach(function (element) {
  68359. element.dispose(camera);
  68360. });
  68361. this._depthOfFieldBlurY.forEach(function (element) {
  68362. element.dispose(camera);
  68363. });
  68364. this._depthOfFieldMerge.dispose(camera);
  68365. };
  68366. return DepthOfFieldEffect;
  68367. }(BABYLON.PostProcessRenderEffect));
  68368. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  68369. })(BABYLON || (BABYLON = {}));
  68370. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  68371. var BABYLON;
  68372. (function (BABYLON) {
  68373. /**
  68374. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  68375. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  68376. */
  68377. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  68378. __extends(DefaultRenderingPipeline, _super);
  68379. /**
  68380. * @constructor
  68381. * @param {string} name - The rendering pipeline name
  68382. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68383. * @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)
  68384. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68385. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  68386. */
  68387. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  68388. if (automaticBuild === void 0) { automaticBuild = true; }
  68389. var _this = _super.call(this, scene.getEngine(), name) || this;
  68390. /**
  68391. * ID of the pass post process used for bloom,
  68392. */
  68393. _this.PassPostProcessId = "PassPostProcessEffect";
  68394. /**
  68395. * ID of the highlight post process used for bloom,
  68396. */
  68397. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  68398. /**
  68399. * ID of the blurX post process used for bloom,
  68400. */
  68401. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  68402. /**
  68403. * ID of the blurY post process used for bloom,
  68404. */
  68405. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  68406. /**
  68407. * ID of the copy back post process used for bloom,
  68408. */
  68409. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  68410. /**
  68411. * ID of the image processing post process;
  68412. */
  68413. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  68414. /**
  68415. * ID of the Fast Approximate Anti-Aliasing post process;
  68416. */
  68417. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  68418. /**
  68419. * ID of the final merge post process;
  68420. */
  68421. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  68422. /**
  68423. * Animations which can be used to tweak settings over a period of time
  68424. */
  68425. _this.animations = [];
  68426. // Values
  68427. _this._bloomEnabled = false;
  68428. _this._depthOfFieldEnabled = false;
  68429. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  68430. _this._fxaaEnabled = false;
  68431. _this._imageProcessingEnabled = true;
  68432. _this._bloomScale = 0.6;
  68433. _this._buildAllowed = true;
  68434. /**
  68435. * Specifies the size of the bloom blur kernel, relative to the final output size
  68436. */
  68437. _this.bloomKernel = 64;
  68438. /**
  68439. * Specifies the weight of the bloom in the final rendering
  68440. */
  68441. _this._bloomWeight = 0.15;
  68442. _this._cameras = cameras || [];
  68443. _this._buildAllowed = automaticBuild;
  68444. // Initialize
  68445. _this._scene = scene;
  68446. var caps = _this._scene.getEngine().getCaps();
  68447. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  68448. // Misc
  68449. if (_this._hdr) {
  68450. if (caps.textureHalfFloatRender) {
  68451. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68452. }
  68453. else if (caps.textureFloatRender) {
  68454. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68455. }
  68456. }
  68457. else {
  68458. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68459. }
  68460. // Attach
  68461. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68462. _this._buildPipeline();
  68463. return _this;
  68464. }
  68465. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  68466. get: function () {
  68467. return this._bloomWeight;
  68468. },
  68469. /**
  68470. * The strength of the bloom.
  68471. */
  68472. set: function (value) {
  68473. if (this._bloomWeight === value) {
  68474. return;
  68475. }
  68476. this._bloomWeight = value;
  68477. if (this._hdr && this.copyBack) {
  68478. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  68479. }
  68480. },
  68481. enumerable: true,
  68482. configurable: true
  68483. });
  68484. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  68485. get: function () {
  68486. return this._bloomScale;
  68487. },
  68488. /**
  68489. * The scale of the bloom, lower value will provide better performance.
  68490. */
  68491. set: function (value) {
  68492. if (this._bloomScale === value) {
  68493. return;
  68494. }
  68495. this._bloomScale = value;
  68496. this._buildPipeline();
  68497. },
  68498. enumerable: true,
  68499. configurable: true
  68500. });
  68501. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  68502. get: function () {
  68503. return this._bloomEnabled;
  68504. },
  68505. /**
  68506. * Enable or disable the bloom from the pipeline
  68507. */
  68508. set: function (enabled) {
  68509. if (this._bloomEnabled === enabled) {
  68510. return;
  68511. }
  68512. this._bloomEnabled = enabled;
  68513. this._buildPipeline();
  68514. },
  68515. enumerable: true,
  68516. configurable: true
  68517. });
  68518. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  68519. /**
  68520. * If the depth of field is enabled.
  68521. */
  68522. get: function () {
  68523. return this._depthOfFieldEnabled;
  68524. },
  68525. set: function (enabled) {
  68526. if (this._depthOfFieldEnabled === enabled) {
  68527. return;
  68528. }
  68529. this._depthOfFieldEnabled = enabled;
  68530. this._buildPipeline();
  68531. },
  68532. enumerable: true,
  68533. configurable: true
  68534. });
  68535. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  68536. /**
  68537. * Blur level of the depth of field effect. (Higher blur will effect performance)
  68538. */
  68539. get: function () {
  68540. return this._depthOfFieldBlurLevel;
  68541. },
  68542. set: function (value) {
  68543. if (this._depthOfFieldBlurLevel === value) {
  68544. return;
  68545. }
  68546. this._depthOfFieldBlurLevel = value;
  68547. this._buildPipeline();
  68548. },
  68549. enumerable: true,
  68550. configurable: true
  68551. });
  68552. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  68553. get: function () {
  68554. return this._fxaaEnabled;
  68555. },
  68556. /**
  68557. * If the anti aliasing is enabled.
  68558. */
  68559. set: function (enabled) {
  68560. if (this._fxaaEnabled === enabled) {
  68561. return;
  68562. }
  68563. this._fxaaEnabled = enabled;
  68564. this._buildPipeline();
  68565. },
  68566. enumerable: true,
  68567. configurable: true
  68568. });
  68569. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  68570. get: function () {
  68571. return this._imageProcessingEnabled;
  68572. },
  68573. /**
  68574. * If image processing is enabled.
  68575. */
  68576. set: function (enabled) {
  68577. if (this._imageProcessingEnabled === enabled) {
  68578. return;
  68579. }
  68580. this._imageProcessingEnabled = enabled;
  68581. this._buildPipeline();
  68582. },
  68583. enumerable: true,
  68584. configurable: true
  68585. });
  68586. /**
  68587. * Force the compilation of the entire pipeline.
  68588. */
  68589. DefaultRenderingPipeline.prototype.prepare = function () {
  68590. var previousState = this._buildAllowed;
  68591. this._buildAllowed = true;
  68592. this._buildPipeline();
  68593. this._buildAllowed = previousState;
  68594. };
  68595. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  68596. var _this = this;
  68597. if (!this._buildAllowed) {
  68598. return;
  68599. }
  68600. var engine = this._scene.getEngine();
  68601. this._disposePostProcesses();
  68602. this._reset();
  68603. if (this.depthOfFieldEnabled) {
  68604. // Enable and get current depth map
  68605. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  68606. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, depthTexture, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  68607. this.addEffect(this.depthOfField);
  68608. }
  68609. if (this.bloomEnabled) {
  68610. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68611. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  68612. if (!this._hdr) {
  68613. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68614. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  68615. this.highlights.autoClear = false;
  68616. this.highlights.alwaysForcePOT = true;
  68617. }
  68618. 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);
  68619. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  68620. this.blurX.alwaysForcePOT = true;
  68621. this.blurX.autoClear = false;
  68622. this.blurX.onActivateObservable.add(function () {
  68623. var dw = _this.blurX.width / engine.getRenderWidth(true);
  68624. _this.blurX.kernel = _this.bloomKernel * dw;
  68625. });
  68626. 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);
  68627. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  68628. this.blurY.alwaysForcePOT = true;
  68629. this.blurY.autoClear = false;
  68630. this.blurY.onActivateObservable.add(function () {
  68631. var dh = _this.blurY.height / engine.getRenderHeight(true);
  68632. _this.blurY.kernel = _this.bloomKernel * dh;
  68633. });
  68634. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68635. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  68636. this.copyBack.alwaysForcePOT = true;
  68637. if (this._hdr) {
  68638. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  68639. var w = this.bloomWeight;
  68640. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  68641. }
  68642. else {
  68643. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  68644. }
  68645. this.copyBack.autoClear = false;
  68646. }
  68647. if (this._imageProcessingEnabled) {
  68648. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68649. if (this._hdr) {
  68650. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  68651. }
  68652. else {
  68653. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  68654. }
  68655. }
  68656. if (this.fxaaEnabled) {
  68657. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68658. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  68659. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  68660. }
  68661. else if (this._hdr && this.imageProcessing) {
  68662. this.finalMerge = this.imageProcessing;
  68663. }
  68664. else {
  68665. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68666. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  68667. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  68668. }
  68669. if (this.bloomEnabled) {
  68670. if (this._hdr) {
  68671. this.copyBack.shareOutputWith(this.blurX);
  68672. if (this.imageProcessing) {
  68673. this.imageProcessing.shareOutputWith(this.pass);
  68674. this.imageProcessing.autoClear = false;
  68675. }
  68676. else if (this.fxaa) {
  68677. this.fxaa.shareOutputWith(this.pass);
  68678. }
  68679. else {
  68680. this.finalMerge.shareOutputWith(this.pass);
  68681. }
  68682. }
  68683. else {
  68684. if (this.fxaa) {
  68685. this.fxaa.shareOutputWith(this.pass);
  68686. }
  68687. else {
  68688. this.finalMerge.shareOutputWith(this.pass);
  68689. }
  68690. }
  68691. }
  68692. if (this._cameras !== null) {
  68693. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  68694. }
  68695. this._enableMSAAOnFirstPostProcess();
  68696. };
  68697. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  68698. for (var i = 0; i < this._cameras.length; i++) {
  68699. var camera = this._cameras[i];
  68700. if (this.pass) {
  68701. this.pass.dispose(camera);
  68702. }
  68703. if (this.highlights) {
  68704. this.highlights.dispose(camera);
  68705. }
  68706. if (this.blurX) {
  68707. this.blurX.dispose(camera);
  68708. }
  68709. if (this.blurY) {
  68710. this.blurY.dispose(camera);
  68711. }
  68712. if (this.copyBack) {
  68713. this.copyBack.dispose(camera);
  68714. }
  68715. if (this.imageProcessing) {
  68716. this.imageProcessing.dispose(camera);
  68717. }
  68718. if (this.fxaa) {
  68719. this.fxaa.dispose(camera);
  68720. }
  68721. if (this.finalMerge) {
  68722. this.finalMerge.dispose(camera);
  68723. }
  68724. if (this.depthOfField) {
  68725. this.depthOfField.disposeEffects(camera);
  68726. }
  68727. }
  68728. this.pass = null;
  68729. this.highlights = null;
  68730. this.blurX = null;
  68731. this.blurY = null;
  68732. this.copyBack = null;
  68733. this.imageProcessing = null;
  68734. this.fxaa = null;
  68735. this.finalMerge = null;
  68736. this.depthOfField = null;
  68737. };
  68738. /**
  68739. * Dispose of the pipeline and stop all post processes
  68740. */
  68741. DefaultRenderingPipeline.prototype.dispose = function () {
  68742. this._disposePostProcesses();
  68743. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  68744. _super.prototype.dispose.call(this);
  68745. };
  68746. /**
  68747. * Serialize the rendering pipeline (Used when exporting)
  68748. * @returns the serialized object
  68749. */
  68750. DefaultRenderingPipeline.prototype.serialize = function () {
  68751. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  68752. serializationObject.customType = "DefaultRenderingPipeline";
  68753. return serializationObject;
  68754. };
  68755. /**
  68756. * Parse the serialized pipeline
  68757. * @param source Source pipeline.
  68758. * @param scene The scene to load the pipeline to.
  68759. * @param rootUrl The URL of the serialized pipeline.
  68760. * @returns An instantiated pipeline from the serialized object.
  68761. */
  68762. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  68763. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  68764. };
  68765. __decorate([
  68766. BABYLON.serialize()
  68767. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  68768. __decorate([
  68769. BABYLON.serialize()
  68770. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  68771. __decorate([
  68772. BABYLON.serialize()
  68773. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  68774. __decorate([
  68775. BABYLON.serialize()
  68776. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  68777. __decorate([
  68778. BABYLON.serialize()
  68779. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  68780. __decorate([
  68781. BABYLON.serialize()
  68782. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  68783. __decorate([
  68784. BABYLON.serialize()
  68785. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  68786. __decorate([
  68787. BABYLON.serialize()
  68788. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  68789. __decorate([
  68790. BABYLON.serialize()
  68791. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  68792. __decorate([
  68793. BABYLON.serialize()
  68794. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  68795. return DefaultRenderingPipeline;
  68796. }(BABYLON.PostProcessRenderPipeline));
  68797. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  68798. })(BABYLON || (BABYLON = {}));
  68799. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  68800. var BABYLON;
  68801. (function (BABYLON) {
  68802. /**
  68803. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  68804. */
  68805. var GeometryBufferRenderer = /** @class */ (function () {
  68806. /**
  68807. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  68808. * @param scene The scene the buffer belongs to
  68809. * @param ratio How big is the buffer related to the main canvas.
  68810. */
  68811. function GeometryBufferRenderer(scene, ratio) {
  68812. if (ratio === void 0) { ratio = 1; }
  68813. this._enablePosition = false;
  68814. this._scene = scene;
  68815. this._ratio = ratio;
  68816. // Render target
  68817. this._createRenderTargets();
  68818. }
  68819. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  68820. /**
  68821. * Set the render list (meshes to be rendered) used in the G buffer.
  68822. */
  68823. set: function (meshes) {
  68824. this._multiRenderTarget.renderList = meshes;
  68825. },
  68826. enumerable: true,
  68827. configurable: true
  68828. });
  68829. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  68830. /**
  68831. * Gets wether or not G buffer are supported by the running hardware.
  68832. * This requires draw buffer supports
  68833. */
  68834. get: function () {
  68835. return this._multiRenderTarget.isSupported;
  68836. },
  68837. enumerable: true,
  68838. configurable: true
  68839. });
  68840. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  68841. /**
  68842. * Gets wether or not position are enabled for the G buffer.
  68843. */
  68844. get: function () {
  68845. return this._enablePosition;
  68846. },
  68847. /**
  68848. * Sets wether or not position are enabled for the G buffer.
  68849. */
  68850. set: function (enable) {
  68851. this._enablePosition = enable;
  68852. this.dispose();
  68853. this._createRenderTargets();
  68854. },
  68855. enumerable: true,
  68856. configurable: true
  68857. });
  68858. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  68859. /**
  68860. * Gets the scene associated with the buffer.
  68861. */
  68862. get: function () {
  68863. return this._scene;
  68864. },
  68865. enumerable: true,
  68866. configurable: true
  68867. });
  68868. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  68869. /**
  68870. * Gets the ratio used by the buffer during its creation.
  68871. * How big is the buffer related to the main canvas.
  68872. */
  68873. get: function () {
  68874. return this._ratio;
  68875. },
  68876. enumerable: true,
  68877. configurable: true
  68878. });
  68879. /**
  68880. * Checks wether everything is ready to render a submesh to the G buffer.
  68881. * @param subMesh the submesh to check readiness for
  68882. * @param useInstances is the mesh drawn using instance or not
  68883. * @returns true if ready otherwise false
  68884. */
  68885. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  68886. var material = subMesh.getMaterial();
  68887. if (material && material.disableDepthWrite) {
  68888. return false;
  68889. }
  68890. var defines = [];
  68891. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  68892. var mesh = subMesh.getMesh();
  68893. // Alpha test
  68894. if (material && material.needAlphaTesting()) {
  68895. defines.push("#define ALPHATEST");
  68896. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68897. attribs.push(BABYLON.VertexBuffer.UVKind);
  68898. defines.push("#define UV1");
  68899. }
  68900. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68901. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68902. defines.push("#define UV2");
  68903. }
  68904. }
  68905. // Buffers
  68906. if (this._enablePosition) {
  68907. defines.push("#define POSITION");
  68908. }
  68909. // Bones
  68910. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68911. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68912. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68913. if (mesh.numBoneInfluencers > 4) {
  68914. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  68915. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  68916. }
  68917. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68918. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  68919. }
  68920. else {
  68921. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68922. }
  68923. // Instances
  68924. if (useInstances) {
  68925. defines.push("#define INSTANCES");
  68926. attribs.push("world0");
  68927. attribs.push("world1");
  68928. attribs.push("world2");
  68929. attribs.push("world3");
  68930. }
  68931. // Get correct effect
  68932. var join = defines.join("\n");
  68933. if (this._cachedDefines !== join) {
  68934. this._cachedDefines = join;
  68935. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  68936. }
  68937. return this._effect.isReady();
  68938. };
  68939. /**
  68940. * Gets the current underlying G Buffer.
  68941. * @returns the buffer
  68942. */
  68943. GeometryBufferRenderer.prototype.getGBuffer = function () {
  68944. return this._multiRenderTarget;
  68945. };
  68946. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  68947. /**
  68948. * Gets the number of samples used to render the buffer (anti aliasing).
  68949. */
  68950. get: function () {
  68951. return this._multiRenderTarget.samples;
  68952. },
  68953. /**
  68954. * Sets the number of samples used to render the buffer (anti aliasing).
  68955. */
  68956. set: function (value) {
  68957. this._multiRenderTarget.samples = value;
  68958. },
  68959. enumerable: true,
  68960. configurable: true
  68961. });
  68962. /**
  68963. * Disposes the renderer and frees up associated resources.
  68964. */
  68965. GeometryBufferRenderer.prototype.dispose = function () {
  68966. this.getGBuffer().dispose();
  68967. };
  68968. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  68969. var _this = this;
  68970. var engine = this._scene.getEngine();
  68971. var count = this._enablePosition ? 3 : 2;
  68972. 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 });
  68973. if (!this.isSupported) {
  68974. return;
  68975. }
  68976. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68977. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68978. this._multiRenderTarget.refreshRate = 1;
  68979. this._multiRenderTarget.renderParticles = false;
  68980. this._multiRenderTarget.renderList = null;
  68981. // set default depth value to 1.0 (far away)
  68982. this._multiRenderTarget.onClearObservable.add(function (engine) {
  68983. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  68984. });
  68985. // Custom render function
  68986. var renderSubMesh = function (subMesh) {
  68987. var mesh = subMesh.getRenderingMesh();
  68988. var scene = _this._scene;
  68989. var engine = scene.getEngine();
  68990. var material = subMesh.getMaterial();
  68991. if (!material) {
  68992. return;
  68993. }
  68994. // Culling
  68995. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  68996. // Managing instances
  68997. var batch = mesh._getInstancesRenderList(subMesh._id);
  68998. if (batch.mustReturn) {
  68999. return;
  69000. }
  69001. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  69002. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  69003. engine.enableEffect(_this._effect);
  69004. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  69005. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  69006. _this._effect.setMatrix("view", scene.getViewMatrix());
  69007. // Alpha test
  69008. if (material && material.needAlphaTesting()) {
  69009. var alphaTexture = material.getAlphaTestTexture();
  69010. if (alphaTexture) {
  69011. _this._effect.setTexture("diffuseSampler", alphaTexture);
  69012. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  69013. }
  69014. }
  69015. // Bones
  69016. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  69017. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  69018. }
  69019. // Draw
  69020. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  69021. }
  69022. };
  69023. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  69024. var index;
  69025. if (depthOnlySubMeshes.length) {
  69026. engine.setColorWrite(false);
  69027. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  69028. renderSubMesh(depthOnlySubMeshes.data[index]);
  69029. }
  69030. engine.setColorWrite(true);
  69031. }
  69032. for (index = 0; index < opaqueSubMeshes.length; index++) {
  69033. renderSubMesh(opaqueSubMeshes.data[index]);
  69034. }
  69035. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  69036. renderSubMesh(alphaTestSubMeshes.data[index]);
  69037. }
  69038. };
  69039. };
  69040. return GeometryBufferRenderer;
  69041. }());
  69042. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  69043. })(BABYLON || (BABYLON = {}));
  69044. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  69045. var BABYLON;
  69046. (function (BABYLON) {
  69047. var RefractionPostProcess = /** @class */ (function (_super) {
  69048. __extends(RefractionPostProcess, _super);
  69049. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  69050. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  69051. _this.color = color;
  69052. _this.depth = depth;
  69053. _this.colorLevel = colorLevel;
  69054. _this._ownRefractionTexture = true;
  69055. _this.onActivateObservable.add(function (cam) {
  69056. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  69057. });
  69058. _this.onApplyObservable.add(function (effect) {
  69059. effect.setColor3("baseColor", _this.color);
  69060. effect.setFloat("depth", _this.depth);
  69061. effect.setFloat("colorLevel", _this.colorLevel);
  69062. effect.setTexture("refractionSampler", _this._refTexture);
  69063. });
  69064. return _this;
  69065. }
  69066. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  69067. /**
  69068. * Gets or sets the refraction texture
  69069. * Please note that you are responsible for disposing the texture if you set it manually
  69070. */
  69071. get: function () {
  69072. return this._refTexture;
  69073. },
  69074. set: function (value) {
  69075. if (this._refTexture && this._ownRefractionTexture) {
  69076. this._refTexture.dispose();
  69077. }
  69078. this._refTexture = value;
  69079. this._ownRefractionTexture = false;
  69080. },
  69081. enumerable: true,
  69082. configurable: true
  69083. });
  69084. // Methods
  69085. RefractionPostProcess.prototype.dispose = function (camera) {
  69086. if (this._refTexture && this._ownRefractionTexture) {
  69087. this._refTexture.dispose();
  69088. this._refTexture = null;
  69089. }
  69090. _super.prototype.dispose.call(this, camera);
  69091. };
  69092. return RefractionPostProcess;
  69093. }(BABYLON.PostProcess));
  69094. BABYLON.RefractionPostProcess = RefractionPostProcess;
  69095. })(BABYLON || (BABYLON = {}));
  69096. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  69097. var BABYLON;
  69098. (function (BABYLON) {
  69099. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  69100. __extends(BlackAndWhitePostProcess, _super);
  69101. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  69102. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  69103. _this.degree = 1;
  69104. _this.onApplyObservable.add(function (effect) {
  69105. effect.setFloat("degree", _this.degree);
  69106. });
  69107. return _this;
  69108. }
  69109. return BlackAndWhitePostProcess;
  69110. }(BABYLON.PostProcess));
  69111. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  69112. })(BABYLON || (BABYLON = {}));
  69113. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  69114. var BABYLON;
  69115. (function (BABYLON) {
  69116. var ConvolutionPostProcess = /** @class */ (function (_super) {
  69117. __extends(ConvolutionPostProcess, _super);
  69118. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  69119. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  69120. _this.kernel = kernel;
  69121. _this.onApply = function (effect) {
  69122. effect.setFloat2("screenSize", _this.width, _this.height);
  69123. effect.setArray("kernel", _this.kernel);
  69124. };
  69125. return _this;
  69126. }
  69127. // Statics
  69128. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  69129. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  69130. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  69131. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  69132. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  69133. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  69134. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  69135. return ConvolutionPostProcess;
  69136. }(BABYLON.PostProcess));
  69137. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  69138. })(BABYLON || (BABYLON = {}));
  69139. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  69140. var BABYLON;
  69141. (function (BABYLON) {
  69142. var FilterPostProcess = /** @class */ (function (_super) {
  69143. __extends(FilterPostProcess, _super);
  69144. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  69145. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  69146. _this.kernelMatrix = kernelMatrix;
  69147. _this.onApply = function (effect) {
  69148. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  69149. };
  69150. return _this;
  69151. }
  69152. return FilterPostProcess;
  69153. }(BABYLON.PostProcess));
  69154. BABYLON.FilterPostProcess = FilterPostProcess;
  69155. })(BABYLON || (BABYLON = {}));
  69156. //# sourceMappingURL=babylon.filterPostProcess.js.map
  69157. var BABYLON;
  69158. (function (BABYLON) {
  69159. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  69160. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  69161. __extends(VolumetricLightScatteringPostProcess, _super);
  69162. /**
  69163. * @constructor
  69164. * @param {string} name - The post-process name
  69165. * @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)
  69166. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  69167. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  69168. * @param {number} samples - The post-process quality, default 100
  69169. * @param {number} samplingMode - The post-process filtering mode
  69170. * @param {BABYLON.Engine} engine - The babylon engine
  69171. * @param {boolean} reusable - If the post-process is reusable
  69172. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  69173. */
  69174. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  69175. if (samples === void 0) { samples = 100; }
  69176. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69177. 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;
  69178. _this._screenCoordinates = BABYLON.Vector2.Zero();
  69179. /**
  69180. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  69181. * @type {Vector3}
  69182. */
  69183. _this.customMeshPosition = BABYLON.Vector3.Zero();
  69184. /**
  69185. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  69186. * @type {boolean}
  69187. */
  69188. _this.useCustomMeshPosition = false;
  69189. /**
  69190. * If the post-process should inverse the light scattering direction
  69191. * @type {boolean}
  69192. */
  69193. _this.invert = true;
  69194. /**
  69195. * Array containing the excluded meshes not rendered in the internal pass
  69196. */
  69197. _this.excludedMeshes = new Array();
  69198. /**
  69199. * Controls the overall intensity of the post-process
  69200. * @type {number}
  69201. */
  69202. _this.exposure = 0.3;
  69203. /**
  69204. * Dissipates each sample's contribution in range [0, 1]
  69205. * @type {number}
  69206. */
  69207. _this.decay = 0.96815;
  69208. /**
  69209. * Controls the overall intensity of each sample
  69210. * @type {number}
  69211. */
  69212. _this.weight = 0.58767;
  69213. /**
  69214. * Controls the density of each sample
  69215. * @type {number}
  69216. */
  69217. _this.density = 0.926;
  69218. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  69219. engine = scene.getEngine();
  69220. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  69221. // Configure mesh
  69222. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  69223. // Configure
  69224. _this._createPass(scene, ratio.passRatio || ratio);
  69225. _this.onActivate = function (camera) {
  69226. if (!_this.isSupported) {
  69227. _this.dispose(camera);
  69228. }
  69229. _this.onActivate = null;
  69230. };
  69231. _this.onApplyObservable.add(function (effect) {
  69232. _this._updateMeshScreenCoordinates(scene);
  69233. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  69234. effect.setFloat("exposure", _this.exposure);
  69235. effect.setFloat("decay", _this.decay);
  69236. effect.setFloat("weight", _this.weight);
  69237. effect.setFloat("density", _this.density);
  69238. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  69239. });
  69240. return _this;
  69241. }
  69242. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  69243. get: function () {
  69244. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  69245. return false;
  69246. },
  69247. set: function (useDiffuseColor) {
  69248. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  69249. },
  69250. enumerable: true,
  69251. configurable: true
  69252. });
  69253. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  69254. return "VolumetricLightScatteringPostProcess";
  69255. };
  69256. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  69257. var mesh = subMesh.getMesh();
  69258. // Render this.mesh as default
  69259. if (mesh === this.mesh && mesh.material) {
  69260. return mesh.material.isReady(mesh);
  69261. }
  69262. var defines = [];
  69263. var attribs = [BABYLON.VertexBuffer.PositionKind];
  69264. var material = subMesh.getMaterial();
  69265. // Alpha test
  69266. if (material) {
  69267. if (material.needAlphaTesting()) {
  69268. defines.push("#define ALPHATEST");
  69269. }
  69270. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  69271. attribs.push(BABYLON.VertexBuffer.UVKind);
  69272. defines.push("#define UV1");
  69273. }
  69274. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  69275. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  69276. defines.push("#define UV2");
  69277. }
  69278. }
  69279. // Bones
  69280. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69281. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  69282. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  69283. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  69284. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  69285. }
  69286. else {
  69287. defines.push("#define NUM_BONE_INFLUENCERS 0");
  69288. }
  69289. // Instances
  69290. if (useInstances) {
  69291. defines.push("#define INSTANCES");
  69292. attribs.push("world0");
  69293. attribs.push("world1");
  69294. attribs.push("world2");
  69295. attribs.push("world3");
  69296. }
  69297. // Get correct effect
  69298. var join = defines.join("\n");
  69299. if (this._cachedDefines !== join) {
  69300. this._cachedDefines = join;
  69301. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  69302. }
  69303. return this._volumetricLightScatteringPass.isReady();
  69304. };
  69305. /**
  69306. * Sets the new light position for light scattering effect
  69307. * @param {BABYLON.Vector3} The new custom light position
  69308. */
  69309. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  69310. this.customMeshPosition = position;
  69311. };
  69312. /**
  69313. * Returns the light position for light scattering effect
  69314. * @return {BABYLON.Vector3} The custom light position
  69315. */
  69316. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  69317. return this.customMeshPosition;
  69318. };
  69319. /**
  69320. * Disposes the internal assets and detaches the post-process from the camera
  69321. */
  69322. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  69323. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  69324. if (rttIndex !== -1) {
  69325. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  69326. }
  69327. this._volumetricLightScatteringRTT.dispose();
  69328. _super.prototype.dispose.call(this, camera);
  69329. };
  69330. /**
  69331. * Returns the render target texture used by the post-process
  69332. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  69333. */
  69334. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  69335. return this._volumetricLightScatteringRTT;
  69336. };
  69337. // Private methods
  69338. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  69339. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  69340. return true;
  69341. }
  69342. return false;
  69343. };
  69344. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  69345. var _this = this;
  69346. var engine = scene.getEngine();
  69347. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  69348. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69349. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69350. this._volumetricLightScatteringRTT.renderList = null;
  69351. this._volumetricLightScatteringRTT.renderParticles = false;
  69352. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  69353. var camera = this.getCamera();
  69354. if (camera) {
  69355. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  69356. }
  69357. else {
  69358. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  69359. }
  69360. // Custom render function for submeshes
  69361. var renderSubMesh = function (subMesh) {
  69362. var mesh = subMesh.getRenderingMesh();
  69363. if (_this._meshExcluded(mesh)) {
  69364. return;
  69365. }
  69366. var material = subMesh.getMaterial();
  69367. if (!material) {
  69368. return;
  69369. }
  69370. var scene = mesh.getScene();
  69371. var engine = scene.getEngine();
  69372. // Culling
  69373. engine.setState(material.backFaceCulling);
  69374. // Managing instances
  69375. var batch = mesh._getInstancesRenderList(subMesh._id);
  69376. if (batch.mustReturn) {
  69377. return;
  69378. }
  69379. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  69380. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  69381. var effect = _this._volumetricLightScatteringPass;
  69382. if (mesh === _this.mesh) {
  69383. if (subMesh.effect) {
  69384. effect = subMesh.effect;
  69385. }
  69386. else {
  69387. effect = material.getEffect();
  69388. }
  69389. }
  69390. engine.enableEffect(effect);
  69391. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  69392. if (mesh === _this.mesh) {
  69393. material.bind(mesh.getWorldMatrix(), mesh);
  69394. }
  69395. else {
  69396. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  69397. // Alpha test
  69398. if (material && material.needAlphaTesting()) {
  69399. var alphaTexture = material.getAlphaTestTexture();
  69400. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  69401. if (alphaTexture) {
  69402. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  69403. }
  69404. }
  69405. // Bones
  69406. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  69407. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  69408. }
  69409. }
  69410. // Draw
  69411. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  69412. }
  69413. };
  69414. // Render target texture callbacks
  69415. var savedSceneClearColor;
  69416. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  69417. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  69418. savedSceneClearColor = scene.clearColor;
  69419. scene.clearColor = sceneClearColor;
  69420. });
  69421. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  69422. scene.clearColor = savedSceneClearColor;
  69423. });
  69424. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  69425. var engine = scene.getEngine();
  69426. var index;
  69427. if (depthOnlySubMeshes.length) {
  69428. engine.setColorWrite(false);
  69429. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  69430. renderSubMesh(depthOnlySubMeshes.data[index]);
  69431. }
  69432. engine.setColorWrite(true);
  69433. }
  69434. for (index = 0; index < opaqueSubMeshes.length; index++) {
  69435. renderSubMesh(opaqueSubMeshes.data[index]);
  69436. }
  69437. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  69438. renderSubMesh(alphaTestSubMeshes.data[index]);
  69439. }
  69440. if (transparentSubMeshes.length) {
  69441. // Sort sub meshes
  69442. for (index = 0; index < transparentSubMeshes.length; index++) {
  69443. var submesh = transparentSubMeshes.data[index];
  69444. var boundingInfo = submesh.getBoundingInfo();
  69445. if (boundingInfo && scene.activeCamera) {
  69446. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  69447. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  69448. }
  69449. }
  69450. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  69451. sortedArray.sort(function (a, b) {
  69452. // Alpha index first
  69453. if (a._alphaIndex > b._alphaIndex) {
  69454. return 1;
  69455. }
  69456. if (a._alphaIndex < b._alphaIndex) {
  69457. return -1;
  69458. }
  69459. // Then distance to camera
  69460. if (a._distanceToCamera < b._distanceToCamera) {
  69461. return 1;
  69462. }
  69463. if (a._distanceToCamera > b._distanceToCamera) {
  69464. return -1;
  69465. }
  69466. return 0;
  69467. });
  69468. // Render sub meshes
  69469. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  69470. for (index = 0; index < sortedArray.length; index++) {
  69471. renderSubMesh(sortedArray[index]);
  69472. }
  69473. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  69474. }
  69475. };
  69476. };
  69477. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  69478. var transform = scene.getTransformMatrix();
  69479. var meshPosition;
  69480. if (this.useCustomMeshPosition) {
  69481. meshPosition = this.customMeshPosition;
  69482. }
  69483. else if (this.attachedNode) {
  69484. meshPosition = this.attachedNode.position;
  69485. }
  69486. else {
  69487. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  69488. }
  69489. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  69490. this._screenCoordinates.x = pos.x / this._viewPort.width;
  69491. this._screenCoordinates.y = pos.y / this._viewPort.height;
  69492. if (this.invert)
  69493. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  69494. };
  69495. // Static methods
  69496. /**
  69497. * Creates a default mesh for the Volumeric Light Scattering post-process
  69498. * @param {string} The mesh name
  69499. * @param {BABYLON.Scene} The scene where to create the mesh
  69500. * @return {BABYLON.Mesh} the default mesh
  69501. */
  69502. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  69503. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  69504. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  69505. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  69506. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  69507. mesh.material = material;
  69508. return mesh;
  69509. };
  69510. __decorate([
  69511. BABYLON.serializeAsVector3()
  69512. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  69513. __decorate([
  69514. BABYLON.serialize()
  69515. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  69516. __decorate([
  69517. BABYLON.serialize()
  69518. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  69519. __decorate([
  69520. BABYLON.serializeAsMeshReference()
  69521. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  69522. __decorate([
  69523. BABYLON.serialize()
  69524. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  69525. __decorate([
  69526. BABYLON.serialize()
  69527. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  69528. __decorate([
  69529. BABYLON.serialize()
  69530. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  69531. __decorate([
  69532. BABYLON.serialize()
  69533. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  69534. __decorate([
  69535. BABYLON.serialize()
  69536. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  69537. return VolumetricLightScatteringPostProcess;
  69538. }(BABYLON.PostProcess));
  69539. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  69540. })(BABYLON || (BABYLON = {}));
  69541. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  69542. //
  69543. // This post-process allows the modification of rendered colors by using
  69544. // a 'look-up table' (LUT). This effect is also called Color Grading.
  69545. //
  69546. // The object needs to be provided an url to a texture containing the color
  69547. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  69548. // Use an image editing software to tweak the LUT to match your needs.
  69549. //
  69550. // For an example of a color LUT, see here:
  69551. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  69552. // For explanations on color grading, see here:
  69553. // http://udn.epicgames.com/Three/ColorGrading.html
  69554. //
  69555. var BABYLON;
  69556. (function (BABYLON) {
  69557. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  69558. __extends(ColorCorrectionPostProcess, _super);
  69559. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  69560. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  69561. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  69562. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  69563. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69564. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69565. _this.onApply = function (effect) {
  69566. effect.setTexture("colorTable", _this._colorTableTexture);
  69567. };
  69568. return _this;
  69569. }
  69570. return ColorCorrectionPostProcess;
  69571. }(BABYLON.PostProcess));
  69572. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  69573. })(BABYLON || (BABYLON = {}));
  69574. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  69575. var BABYLON;
  69576. (function (BABYLON) {
  69577. var TonemappingOperator;
  69578. (function (TonemappingOperator) {
  69579. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  69580. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  69581. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  69582. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  69583. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  69584. ;
  69585. var TonemapPostProcess = /** @class */ (function (_super) {
  69586. __extends(TonemapPostProcess, _super);
  69587. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  69588. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69589. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69590. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  69591. _this._operator = _operator;
  69592. _this.exposureAdjustment = exposureAdjustment;
  69593. var defines = "#define ";
  69594. if (_this._operator === TonemappingOperator.Hable)
  69595. defines += "HABLE_TONEMAPPING";
  69596. else if (_this._operator === TonemappingOperator.Reinhard)
  69597. defines += "REINHARD_TONEMAPPING";
  69598. else if (_this._operator === TonemappingOperator.HejiDawson)
  69599. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  69600. else if (_this._operator === TonemappingOperator.Photographic)
  69601. defines += "PHOTOGRAPHIC_TONEMAPPING";
  69602. //sadly a second call to create the effect.
  69603. _this.updateEffect(defines);
  69604. _this.onApply = function (effect) {
  69605. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  69606. };
  69607. return _this;
  69608. }
  69609. return TonemapPostProcess;
  69610. }(BABYLON.PostProcess));
  69611. BABYLON.TonemapPostProcess = TonemapPostProcess;
  69612. })(BABYLON || (BABYLON = {}));
  69613. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  69614. var BABYLON;
  69615. (function (BABYLON) {
  69616. var DisplayPassPostProcess = /** @class */ (function (_super) {
  69617. __extends(DisplayPassPostProcess, _super);
  69618. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  69619. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  69620. }
  69621. return DisplayPassPostProcess;
  69622. }(BABYLON.PostProcess));
  69623. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  69624. })(BABYLON || (BABYLON = {}));
  69625. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  69626. var BABYLON;
  69627. (function (BABYLON) {
  69628. var HighlightsPostProcess = /** @class */ (function (_super) {
  69629. __extends(HighlightsPostProcess, _super);
  69630. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  69631. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69632. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  69633. }
  69634. return HighlightsPostProcess;
  69635. }(BABYLON.PostProcess));
  69636. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  69637. })(BABYLON || (BABYLON = {}));
  69638. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  69639. var BABYLON;
  69640. (function (BABYLON) {
  69641. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  69642. __extends(ImageProcessingPostProcess, _super);
  69643. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  69644. if (camera === void 0) { camera = null; }
  69645. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69646. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  69647. _this._fromLinearSpace = true;
  69648. /**
  69649. * Defines cache preventing GC.
  69650. */
  69651. _this._defines = {
  69652. IMAGEPROCESSING: false,
  69653. VIGNETTE: false,
  69654. VIGNETTEBLENDMODEMULTIPLY: false,
  69655. VIGNETTEBLENDMODEOPAQUE: false,
  69656. TONEMAPPING: false,
  69657. CONTRAST: false,
  69658. COLORCURVES: false,
  69659. COLORGRADING: false,
  69660. COLORGRADING3D: false,
  69661. FROMLINEARSPACE: false,
  69662. SAMPLER3DGREENDEPTH: false,
  69663. SAMPLER3DBGRMAP: false,
  69664. IMAGEPROCESSINGPOSTPROCESS: false,
  69665. EXPOSURE: false,
  69666. };
  69667. // Setup the configuration as forced by the constructor. This would then not force the
  69668. // scene materials output in linear space and let untouched the default forward pass.
  69669. if (imageProcessingConfiguration) {
  69670. imageProcessingConfiguration.applyByPostProcess = true;
  69671. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  69672. // This will cause the shader to be compiled
  69673. _this.fromLinearSpace = false;
  69674. }
  69675. else {
  69676. _this._attachImageProcessingConfiguration(null, true);
  69677. _this.imageProcessingConfiguration.applyByPostProcess = true;
  69678. }
  69679. _this.onApply = function (effect) {
  69680. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  69681. };
  69682. return _this;
  69683. }
  69684. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  69685. /**
  69686. * Gets the image processing configuration used either in this material.
  69687. */
  69688. get: function () {
  69689. return this._imageProcessingConfiguration;
  69690. },
  69691. /**
  69692. * Sets the Default image processing configuration used either in the this material.
  69693. *
  69694. * If sets to null, the scene one is in use.
  69695. */
  69696. set: function (value) {
  69697. this._attachImageProcessingConfiguration(value);
  69698. },
  69699. enumerable: true,
  69700. configurable: true
  69701. });
  69702. /**
  69703. * Attaches a new image processing configuration to the PBR Material.
  69704. * @param configuration
  69705. */
  69706. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  69707. var _this = this;
  69708. if (doNotBuild === void 0) { doNotBuild = false; }
  69709. if (configuration === this._imageProcessingConfiguration) {
  69710. return;
  69711. }
  69712. // Detaches observer.
  69713. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  69714. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  69715. }
  69716. // Pick the scene configuration if needed.
  69717. if (!configuration) {
  69718. var scene = null;
  69719. var engine = this.getEngine();
  69720. var camera = this.getCamera();
  69721. if (camera) {
  69722. scene = camera.getScene();
  69723. }
  69724. else if (engine && engine.scenes) {
  69725. var scenes = engine.scenes;
  69726. scene = scenes[scenes.length - 1];
  69727. }
  69728. else {
  69729. scene = BABYLON.Engine.LastCreatedScene;
  69730. }
  69731. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  69732. }
  69733. else {
  69734. this._imageProcessingConfiguration = configuration;
  69735. }
  69736. // Attaches observer.
  69737. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  69738. _this._updateParameters();
  69739. });
  69740. // Ensure the effect will be rebuilt.
  69741. if (!doNotBuild) {
  69742. this._updateParameters();
  69743. }
  69744. };
  69745. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  69746. /**
  69747. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  69748. */
  69749. get: function () {
  69750. return this.imageProcessingConfiguration.colorCurves;
  69751. },
  69752. /**
  69753. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  69754. */
  69755. set: function (value) {
  69756. this.imageProcessingConfiguration.colorCurves = value;
  69757. },
  69758. enumerable: true,
  69759. configurable: true
  69760. });
  69761. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  69762. /**
  69763. * Gets wether the color curves effect is enabled.
  69764. */
  69765. get: function () {
  69766. return this.imageProcessingConfiguration.colorCurvesEnabled;
  69767. },
  69768. /**
  69769. * Sets wether the color curves effect is enabled.
  69770. */
  69771. set: function (value) {
  69772. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  69773. },
  69774. enumerable: true,
  69775. configurable: true
  69776. });
  69777. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  69778. /**
  69779. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  69780. */
  69781. get: function () {
  69782. return this.imageProcessingConfiguration.colorGradingTexture;
  69783. },
  69784. /**
  69785. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  69786. */
  69787. set: function (value) {
  69788. this.imageProcessingConfiguration.colorGradingTexture = value;
  69789. },
  69790. enumerable: true,
  69791. configurable: true
  69792. });
  69793. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  69794. /**
  69795. * Gets wether the color grading effect is enabled.
  69796. */
  69797. get: function () {
  69798. return this.imageProcessingConfiguration.colorGradingEnabled;
  69799. },
  69800. /**
  69801. * Gets wether the color grading effect is enabled.
  69802. */
  69803. set: function (value) {
  69804. this.imageProcessingConfiguration.colorGradingEnabled = value;
  69805. },
  69806. enumerable: true,
  69807. configurable: true
  69808. });
  69809. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  69810. /**
  69811. * Gets exposure used in the effect.
  69812. */
  69813. get: function () {
  69814. return this.imageProcessingConfiguration.exposure;
  69815. },
  69816. /**
  69817. * Sets exposure used in the effect.
  69818. */
  69819. set: function (value) {
  69820. this.imageProcessingConfiguration.exposure = value;
  69821. },
  69822. enumerable: true,
  69823. configurable: true
  69824. });
  69825. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  69826. /**
  69827. * Gets wether tonemapping is enabled or not.
  69828. */
  69829. get: function () {
  69830. return this._imageProcessingConfiguration.toneMappingEnabled;
  69831. },
  69832. /**
  69833. * Sets wether tonemapping is enabled or not
  69834. */
  69835. set: function (value) {
  69836. this._imageProcessingConfiguration.toneMappingEnabled = value;
  69837. },
  69838. enumerable: true,
  69839. configurable: true
  69840. });
  69841. ;
  69842. ;
  69843. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  69844. /**
  69845. * Gets contrast used in the effect.
  69846. */
  69847. get: function () {
  69848. return this.imageProcessingConfiguration.contrast;
  69849. },
  69850. /**
  69851. * Sets contrast used in the effect.
  69852. */
  69853. set: function (value) {
  69854. this.imageProcessingConfiguration.contrast = value;
  69855. },
  69856. enumerable: true,
  69857. configurable: true
  69858. });
  69859. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  69860. /**
  69861. * Gets Vignette stretch size.
  69862. */
  69863. get: function () {
  69864. return this.imageProcessingConfiguration.vignetteStretch;
  69865. },
  69866. /**
  69867. * Sets Vignette stretch size.
  69868. */
  69869. set: function (value) {
  69870. this.imageProcessingConfiguration.vignetteStretch = value;
  69871. },
  69872. enumerable: true,
  69873. configurable: true
  69874. });
  69875. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  69876. /**
  69877. * Gets Vignette centre X Offset.
  69878. */
  69879. get: function () {
  69880. return this.imageProcessingConfiguration.vignetteCentreX;
  69881. },
  69882. /**
  69883. * Sets Vignette centre X Offset.
  69884. */
  69885. set: function (value) {
  69886. this.imageProcessingConfiguration.vignetteCentreX = value;
  69887. },
  69888. enumerable: true,
  69889. configurable: true
  69890. });
  69891. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  69892. /**
  69893. * Gets Vignette centre Y Offset.
  69894. */
  69895. get: function () {
  69896. return this.imageProcessingConfiguration.vignetteCentreY;
  69897. },
  69898. /**
  69899. * Sets Vignette centre Y Offset.
  69900. */
  69901. set: function (value) {
  69902. this.imageProcessingConfiguration.vignetteCentreY = value;
  69903. },
  69904. enumerable: true,
  69905. configurable: true
  69906. });
  69907. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  69908. /**
  69909. * Gets Vignette weight or intensity of the vignette effect.
  69910. */
  69911. get: function () {
  69912. return this.imageProcessingConfiguration.vignetteWeight;
  69913. },
  69914. /**
  69915. * Sets Vignette weight or intensity of the vignette effect.
  69916. */
  69917. set: function (value) {
  69918. this.imageProcessingConfiguration.vignetteWeight = value;
  69919. },
  69920. enumerable: true,
  69921. configurable: true
  69922. });
  69923. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  69924. /**
  69925. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  69926. * if vignetteEnabled is set to true.
  69927. */
  69928. get: function () {
  69929. return this.imageProcessingConfiguration.vignetteColor;
  69930. },
  69931. /**
  69932. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  69933. * if vignetteEnabled is set to true.
  69934. */
  69935. set: function (value) {
  69936. this.imageProcessingConfiguration.vignetteColor = value;
  69937. },
  69938. enumerable: true,
  69939. configurable: true
  69940. });
  69941. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  69942. /**
  69943. * Gets Camera field of view used by the Vignette effect.
  69944. */
  69945. get: function () {
  69946. return this.imageProcessingConfiguration.vignetteCameraFov;
  69947. },
  69948. /**
  69949. * Sets Camera field of view used by the Vignette effect.
  69950. */
  69951. set: function (value) {
  69952. this.imageProcessingConfiguration.vignetteCameraFov = value;
  69953. },
  69954. enumerable: true,
  69955. configurable: true
  69956. });
  69957. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  69958. /**
  69959. * Gets the vignette blend mode allowing different kind of effect.
  69960. */
  69961. get: function () {
  69962. return this.imageProcessingConfiguration.vignetteBlendMode;
  69963. },
  69964. /**
  69965. * Sets the vignette blend mode allowing different kind of effect.
  69966. */
  69967. set: function (value) {
  69968. this.imageProcessingConfiguration.vignetteBlendMode = value;
  69969. },
  69970. enumerable: true,
  69971. configurable: true
  69972. });
  69973. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  69974. /**
  69975. * Gets wether the vignette effect is enabled.
  69976. */
  69977. get: function () {
  69978. return this.imageProcessingConfiguration.vignetteEnabled;
  69979. },
  69980. /**
  69981. * Sets wether the vignette effect is enabled.
  69982. */
  69983. set: function (value) {
  69984. this.imageProcessingConfiguration.vignetteEnabled = value;
  69985. },
  69986. enumerable: true,
  69987. configurable: true
  69988. });
  69989. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  69990. /**
  69991. * Gets wether the input of the processing is in Gamma or Linear Space.
  69992. */
  69993. get: function () {
  69994. return this._fromLinearSpace;
  69995. },
  69996. /**
  69997. * Sets wether the input of the processing is in Gamma or Linear Space.
  69998. */
  69999. set: function (value) {
  70000. if (this._fromLinearSpace === value) {
  70001. return;
  70002. }
  70003. this._fromLinearSpace = value;
  70004. this._updateParameters();
  70005. },
  70006. enumerable: true,
  70007. configurable: true
  70008. });
  70009. ImageProcessingPostProcess.prototype.getClassName = function () {
  70010. return "ImageProcessingPostProcess";
  70011. };
  70012. ImageProcessingPostProcess.prototype._updateParameters = function () {
  70013. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  70014. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  70015. var defines = "";
  70016. for (var define in this._defines) {
  70017. if (this._defines[define]) {
  70018. defines += "#define " + define + ";\r\n";
  70019. }
  70020. }
  70021. var samplers = ["textureSampler"];
  70022. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  70023. var uniforms = ["scale"];
  70024. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  70025. this.updateEffect(defines, uniforms, samplers);
  70026. };
  70027. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  70028. _super.prototype.dispose.call(this, camera);
  70029. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  70030. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  70031. }
  70032. this.imageProcessingConfiguration.applyByPostProcess = false;
  70033. };
  70034. __decorate([
  70035. BABYLON.serialize()
  70036. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  70037. return ImageProcessingPostProcess;
  70038. }(BABYLON.PostProcess));
  70039. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  70040. })(BABYLON || (BABYLON = {}));
  70041. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  70042. var BABYLON;
  70043. (function (BABYLON) {
  70044. /**
  70045. * The Blur Post Process which blurs an image based on a kernel and direction.
  70046. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  70047. */
  70048. var BlurPostProcess = /** @class */ (function (_super) {
  70049. __extends(BlurPostProcess, _super);
  70050. /**
  70051. * Creates a new instance of @see BlurPostProcess
  70052. * @param name The name of the effect.
  70053. * @param direction The direction in which to blur the image.
  70054. * @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.
  70055. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  70056. * @param camera The camera to apply the render pass to.
  70057. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70058. * @param engine The engine which the post process will be applied. (default: current engine)
  70059. * @param reusable If the post process can be reused on the same frame. (default: false)
  70060. * @param textureType Type of textures used when performing the post process. (default: 0)
  70061. */
  70062. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines) {
  70063. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70064. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70065. if (defines === void 0) { defines = ""; }
  70066. 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;
  70067. _this.direction = direction;
  70068. _this._packedFloat = false;
  70069. _this._staticDefines = "";
  70070. _this._staticDefines = defines;
  70071. _this.onApplyObservable.add(function (effect) {
  70072. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  70073. });
  70074. _this.kernel = kernel;
  70075. return _this;
  70076. }
  70077. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  70078. /**
  70079. * Gets the length in pixels of the blur sample region
  70080. */
  70081. get: function () {
  70082. return this._idealKernel;
  70083. },
  70084. /**
  70085. * Sets the length in pixels of the blur sample region
  70086. */
  70087. set: function (v) {
  70088. if (this._idealKernel === v) {
  70089. return;
  70090. }
  70091. v = Math.max(v, 1);
  70092. this._idealKernel = v;
  70093. this._kernel = this._nearestBestKernel(v);
  70094. this._updateParameters();
  70095. },
  70096. enumerable: true,
  70097. configurable: true
  70098. });
  70099. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  70100. /**
  70101. * Gets wether or not the blur is unpacking/repacking floats
  70102. */
  70103. get: function () {
  70104. return this._packedFloat;
  70105. },
  70106. /**
  70107. * Sets wether or not the blur needs to unpack/repack floats
  70108. */
  70109. set: function (v) {
  70110. if (this._packedFloat === v) {
  70111. return;
  70112. }
  70113. this._packedFloat = v;
  70114. this._updateParameters();
  70115. },
  70116. enumerable: true,
  70117. configurable: true
  70118. });
  70119. BlurPostProcess.prototype._updateParameters = function () {
  70120. // Generate sampling offsets and weights
  70121. var N = this._kernel;
  70122. var centerIndex = (N - 1) / 2;
  70123. // Generate Gaussian sampling weights over kernel
  70124. var offsets = [];
  70125. var weights = [];
  70126. var totalWeight = 0;
  70127. for (var i = 0; i < N; i++) {
  70128. var u = i / (N - 1);
  70129. var w = this._gaussianWeight(u * 2.0 - 1);
  70130. offsets[i] = (i - centerIndex);
  70131. weights[i] = w;
  70132. totalWeight += w;
  70133. }
  70134. // Normalize weights
  70135. for (var i = 0; i < weights.length; i++) {
  70136. weights[i] /= totalWeight;
  70137. }
  70138. // Optimize: combine samples to take advantage of hardware linear sampling
  70139. // Walk from left to center, combining pairs (symmetrically)
  70140. var linearSamplingWeights = [];
  70141. var linearSamplingOffsets = [];
  70142. var linearSamplingMap = [];
  70143. for (var i = 0; i <= centerIndex; i += 2) {
  70144. var j = Math.min(i + 1, Math.floor(centerIndex));
  70145. var singleCenterSample = i === j;
  70146. if (singleCenterSample) {
  70147. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  70148. }
  70149. else {
  70150. var sharedCell = j === centerIndex;
  70151. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  70152. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  70153. if (offsetLinear === 0) {
  70154. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  70155. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  70156. }
  70157. else {
  70158. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  70159. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  70160. }
  70161. }
  70162. }
  70163. for (var i = 0; i < linearSamplingMap.length; i++) {
  70164. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  70165. linearSamplingWeights[i] = linearSamplingMap[i].w;
  70166. }
  70167. // Replace with optimized
  70168. offsets = linearSamplingOffsets;
  70169. weights = linearSamplingWeights;
  70170. // Generate shaders
  70171. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  70172. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  70173. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  70174. var defines = "";
  70175. defines += this._staticDefines;
  70176. for (var i = 0; i < varyingCount; i++) {
  70177. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  70178. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  70179. }
  70180. var depCount = 0;
  70181. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  70182. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  70183. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  70184. depCount++;
  70185. }
  70186. if (this.packedFloat) {
  70187. defines += "#define PACKEDFLOAT 1";
  70188. }
  70189. this.updateEffect(defines, null, null, {
  70190. varyingCount: varyingCount,
  70191. depCount: depCount
  70192. });
  70193. };
  70194. /**
  70195. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  70196. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  70197. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  70198. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  70199. * The gaps between physical kernels are compensated for in the weighting of the samples
  70200. * @param idealKernel Ideal blur kernel.
  70201. * @return Nearest best kernel.
  70202. */
  70203. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  70204. var v = Math.round(idealKernel);
  70205. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  70206. var k = _a[_i];
  70207. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  70208. return Math.max(k, 3);
  70209. }
  70210. }
  70211. return Math.max(v, 3);
  70212. };
  70213. /**
  70214. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  70215. * @param x The point on the Gaussian distribution to sample.
  70216. * @return the value of the Gaussian function at x.
  70217. */
  70218. BlurPostProcess.prototype._gaussianWeight = function (x) {
  70219. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  70220. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  70221. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  70222. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  70223. // truncated at around 1.3% of peak strength.
  70224. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  70225. var sigma = (1 / 3);
  70226. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  70227. var exponent = -((x * x) / (2.0 * sigma * sigma));
  70228. var weight = (1.0 / denominator) * Math.exp(exponent);
  70229. return weight;
  70230. };
  70231. /**
  70232. * Generates a string that can be used as a floating point number in GLSL.
  70233. * @param x Value to print.
  70234. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  70235. * @return GLSL float string.
  70236. */
  70237. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  70238. if (decimalFigures === void 0) { decimalFigures = 8; }
  70239. return x.toFixed(decimalFigures).replace(/0+$/, '');
  70240. };
  70241. return BlurPostProcess;
  70242. }(BABYLON.PostProcess));
  70243. BABYLON.BlurPostProcess = BlurPostProcess;
  70244. })(BABYLON || (BABYLON = {}));
  70245. //# sourceMappingURL=babylon.blurPostProcess.js.map
  70246. var BABYLON;
  70247. (function (BABYLON) {
  70248. /**
  70249. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  70250. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  70251. * based on samples that have a large difference in distance than the center pixel.
  70252. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  70253. */
  70254. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  70255. __extends(DepthOfFieldBlurPostProcess, _super);
  70256. /**
  70257. * Creates a new instance of @see CircleOfConfusionPostProcess
  70258. * @param name The name of the effect.
  70259. * @param scene The scene the effect belongs to.
  70260. * @param direction The direction the blur should be applied.
  70261. * @param kernel The size of the kernel used to blur.
  70262. * @param options The required width/height ratio to downsize to before computing the render pass.
  70263. * @param camera The camera to apply the render pass to.
  70264. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  70265. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  70266. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70267. * @param engine The engine which the post process will be applied. (default: current engine)
  70268. * @param reusable If the post process can be reused on the same frame. (default: false)
  70269. * @param textureType Type of textures used when performing the post process. (default: 0)
  70270. */
  70271. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType) {
  70272. if (imageToBlur === void 0) { imageToBlur = null; }
  70273. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70274. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70275. 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;
  70276. _this.direction = direction;
  70277. _this.onApplyObservable.add(function (effect) {
  70278. if (imageToBlur != null) {
  70279. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  70280. }
  70281. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  70282. if (scene.activeCamera) {
  70283. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  70284. }
  70285. });
  70286. return _this;
  70287. }
  70288. return DepthOfFieldBlurPostProcess;
  70289. }(BABYLON.BlurPostProcess));
  70290. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  70291. })(BABYLON || (BABYLON = {}));
  70292. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  70293. var BABYLON;
  70294. (function (BABYLON) {
  70295. var Bone = /** @class */ (function (_super) {
  70296. __extends(Bone, _super);
  70297. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  70298. if (parentBone === void 0) { parentBone = null; }
  70299. if (localMatrix === void 0) { localMatrix = null; }
  70300. if (restPose === void 0) { restPose = null; }
  70301. if (baseMatrix === void 0) { baseMatrix = null; }
  70302. if (index === void 0) { index = null; }
  70303. var _this = _super.call(this, name, skeleton.getScene()) || this;
  70304. _this.name = name;
  70305. _this.children = new Array();
  70306. _this.animations = new Array();
  70307. // Set this value to map this bone to a different index in the transform matrices.
  70308. // Set this value to -1 to exclude the bone from the transform matrices.
  70309. _this._index = null;
  70310. _this._worldTransform = new BABYLON.Matrix();
  70311. _this._absoluteTransform = new BABYLON.Matrix();
  70312. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  70313. _this._scaleMatrix = BABYLON.Matrix.Identity();
  70314. _this._scaleVector = BABYLON.Vector3.One();
  70315. _this._negateScaleChildren = BABYLON.Vector3.One();
  70316. _this._scalingDeterminant = 1;
  70317. _this._skeleton = skeleton;
  70318. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  70319. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  70320. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  70321. _this._index = index;
  70322. skeleton.bones.push(_this);
  70323. _this.setParent(parentBone, false);
  70324. _this._updateDifferenceMatrix();
  70325. return _this;
  70326. }
  70327. Object.defineProperty(Bone.prototype, "_matrix", {
  70328. get: function () {
  70329. return this._localMatrix;
  70330. },
  70331. set: function (val) {
  70332. if (this._localMatrix) {
  70333. this._localMatrix.copyFrom(val);
  70334. }
  70335. else {
  70336. this._localMatrix = val;
  70337. }
  70338. },
  70339. enumerable: true,
  70340. configurable: true
  70341. });
  70342. // Members
  70343. Bone.prototype.getSkeleton = function () {
  70344. return this._skeleton;
  70345. };
  70346. Bone.prototype.getParent = function () {
  70347. return this._parent;
  70348. };
  70349. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  70350. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  70351. if (this._parent === parent) {
  70352. return;
  70353. }
  70354. if (this._parent) {
  70355. var index = this._parent.children.indexOf(this);
  70356. if (index !== -1) {
  70357. this._parent.children.splice(index, 1);
  70358. }
  70359. }
  70360. this._parent = parent;
  70361. if (this._parent) {
  70362. this._parent.children.push(this);
  70363. }
  70364. if (updateDifferenceMatrix) {
  70365. this._updateDifferenceMatrix();
  70366. }
  70367. };
  70368. Bone.prototype.getLocalMatrix = function () {
  70369. return this._localMatrix;
  70370. };
  70371. Bone.prototype.getBaseMatrix = function () {
  70372. return this._baseMatrix;
  70373. };
  70374. Bone.prototype.getRestPose = function () {
  70375. return this._restPose;
  70376. };
  70377. Bone.prototype.returnToRest = function () {
  70378. this.updateMatrix(this._restPose.clone());
  70379. };
  70380. Bone.prototype.getWorldMatrix = function () {
  70381. return this._worldTransform;
  70382. };
  70383. Bone.prototype.getInvertedAbsoluteTransform = function () {
  70384. return this._invertedAbsoluteTransform;
  70385. };
  70386. Bone.prototype.getAbsoluteTransform = function () {
  70387. return this._absoluteTransform;
  70388. };
  70389. Object.defineProperty(Bone.prototype, "position", {
  70390. // Properties (matches AbstractMesh properties)
  70391. get: function () {
  70392. return this.getPosition();
  70393. },
  70394. set: function (newPosition) {
  70395. this.setPosition(newPosition);
  70396. },
  70397. enumerable: true,
  70398. configurable: true
  70399. });
  70400. Object.defineProperty(Bone.prototype, "rotation", {
  70401. get: function () {
  70402. return this.getRotation();
  70403. },
  70404. set: function (newRotation) {
  70405. this.setRotation(newRotation);
  70406. },
  70407. enumerable: true,
  70408. configurable: true
  70409. });
  70410. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  70411. get: function () {
  70412. return this.getRotationQuaternion();
  70413. },
  70414. set: function (newRotation) {
  70415. this.setRotationQuaternion(newRotation);
  70416. },
  70417. enumerable: true,
  70418. configurable: true
  70419. });
  70420. Object.defineProperty(Bone.prototype, "scaling", {
  70421. get: function () {
  70422. return this.getScale();
  70423. },
  70424. set: function (newScaling) {
  70425. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  70426. },
  70427. enumerable: true,
  70428. configurable: true
  70429. });
  70430. // Methods
  70431. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  70432. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  70433. this._baseMatrix = matrix.clone();
  70434. this._localMatrix = matrix.clone();
  70435. this._skeleton._markAsDirty();
  70436. if (updateDifferenceMatrix) {
  70437. this._updateDifferenceMatrix();
  70438. }
  70439. };
  70440. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  70441. if (!rootMatrix) {
  70442. rootMatrix = this._baseMatrix;
  70443. }
  70444. if (this._parent) {
  70445. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  70446. }
  70447. else {
  70448. this._absoluteTransform.copyFrom(rootMatrix);
  70449. }
  70450. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  70451. for (var index = 0; index < this.children.length; index++) {
  70452. this.children[index]._updateDifferenceMatrix();
  70453. }
  70454. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  70455. };
  70456. Bone.prototype.markAsDirty = function () {
  70457. this._currentRenderId++;
  70458. this._skeleton._markAsDirty();
  70459. };
  70460. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  70461. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  70462. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  70463. // all animation may be coming from a library skeleton, so may need to create animation
  70464. if (this.animations.length === 0) {
  70465. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  70466. this.animations[0].setKeys([]);
  70467. }
  70468. // get animation info / verify there is such a range from the source bone
  70469. var sourceRange = source.animations[0].getRange(rangeName);
  70470. if (!sourceRange) {
  70471. return false;
  70472. }
  70473. var from = sourceRange.from;
  70474. var to = sourceRange.to;
  70475. var sourceKeys = source.animations[0].getKeys();
  70476. // rescaling prep
  70477. var sourceBoneLength = source.length;
  70478. var sourceParent = source.getParent();
  70479. var parent = this.getParent();
  70480. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  70481. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  70482. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  70483. var destKeys = this.animations[0].getKeys();
  70484. // loop vars declaration
  70485. var orig;
  70486. var origTranslation;
  70487. var mat;
  70488. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  70489. orig = sourceKeys[key];
  70490. if (orig.frame >= from && orig.frame <= to) {
  70491. if (rescaleAsRequired) {
  70492. mat = orig.value.clone();
  70493. // scale based on parent ratio, when bone has parent
  70494. if (parentScalingReqd) {
  70495. origTranslation = mat.getTranslation();
  70496. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  70497. // scale based on skeleton dimension ratio when root bone, and value is passed
  70498. }
  70499. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  70500. origTranslation = mat.getTranslation();
  70501. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  70502. // use original when root bone, and no data for skelDimensionsRatio
  70503. }
  70504. else {
  70505. mat = orig.value;
  70506. }
  70507. }
  70508. else {
  70509. mat = orig.value;
  70510. }
  70511. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  70512. }
  70513. }
  70514. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  70515. return true;
  70516. };
  70517. /**
  70518. * Translate the bone in local or world space.
  70519. * @param vec The amount to translate the bone.
  70520. * @param space The space that the translation is in.
  70521. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70522. */
  70523. Bone.prototype.translate = function (vec, space, mesh) {
  70524. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70525. var lm = this.getLocalMatrix();
  70526. if (space == BABYLON.Space.LOCAL) {
  70527. lm.m[12] += vec.x;
  70528. lm.m[13] += vec.y;
  70529. lm.m[14] += vec.z;
  70530. }
  70531. else {
  70532. var wm = null;
  70533. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70534. if (mesh) {
  70535. wm = mesh.getWorldMatrix();
  70536. }
  70537. this._skeleton.computeAbsoluteTransforms();
  70538. var tmat = Bone._tmpMats[0];
  70539. var tvec = Bone._tmpVecs[0];
  70540. if (this._parent) {
  70541. if (mesh && wm) {
  70542. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70543. tmat.multiplyToRef(wm, tmat);
  70544. }
  70545. else {
  70546. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70547. }
  70548. }
  70549. tmat.m[12] = 0;
  70550. tmat.m[13] = 0;
  70551. tmat.m[14] = 0;
  70552. tmat.invert();
  70553. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  70554. lm.m[12] += tvec.x;
  70555. lm.m[13] += tvec.y;
  70556. lm.m[14] += tvec.z;
  70557. }
  70558. this.markAsDirty();
  70559. };
  70560. /**
  70561. * Set the postion of the bone in local or world space.
  70562. * @param position The position to set the bone.
  70563. * @param space The space that the position is in.
  70564. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70565. */
  70566. Bone.prototype.setPosition = function (position, space, mesh) {
  70567. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70568. var lm = this.getLocalMatrix();
  70569. if (space == BABYLON.Space.LOCAL) {
  70570. lm.m[12] = position.x;
  70571. lm.m[13] = position.y;
  70572. lm.m[14] = position.z;
  70573. }
  70574. else {
  70575. var wm = null;
  70576. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70577. if (mesh) {
  70578. wm = mesh.getWorldMatrix();
  70579. }
  70580. this._skeleton.computeAbsoluteTransforms();
  70581. var tmat = Bone._tmpMats[0];
  70582. var vec = Bone._tmpVecs[0];
  70583. if (this._parent) {
  70584. if (mesh && wm) {
  70585. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70586. tmat.multiplyToRef(wm, tmat);
  70587. }
  70588. else {
  70589. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70590. }
  70591. }
  70592. tmat.invert();
  70593. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  70594. lm.m[12] = vec.x;
  70595. lm.m[13] = vec.y;
  70596. lm.m[14] = vec.z;
  70597. }
  70598. this.markAsDirty();
  70599. };
  70600. /**
  70601. * Set the absolute postion of the bone (world space).
  70602. * @param position The position to set the bone.
  70603. * @param mesh The mesh that this bone is attached to.
  70604. */
  70605. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  70606. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  70607. };
  70608. /**
  70609. * Set the scale of the bone on the x, y and z axes.
  70610. * @param x The scale of the bone on the x axis.
  70611. * @param x The scale of the bone on the y axis.
  70612. * @param z The scale of the bone on the z axis.
  70613. * @param scaleChildren Set this to true if children of the bone should be scaled.
  70614. */
  70615. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  70616. if (scaleChildren === void 0) { scaleChildren = false; }
  70617. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  70618. if (!scaleChildren) {
  70619. this._negateScaleChildren.x = 1 / x;
  70620. this._negateScaleChildren.y = 1 / y;
  70621. this._negateScaleChildren.z = 1 / z;
  70622. }
  70623. this._syncScaleVector();
  70624. }
  70625. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  70626. };
  70627. /**
  70628. * Scale the bone on the x, y and z axes.
  70629. * @param x The amount to scale the bone on the x axis.
  70630. * @param x The amount to scale the bone on the y axis.
  70631. * @param z The amount to scale the bone on the z axis.
  70632. * @param scaleChildren Set this to true if children of the bone should be scaled.
  70633. */
  70634. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  70635. if (scaleChildren === void 0) { scaleChildren = false; }
  70636. var locMat = this.getLocalMatrix();
  70637. var origLocMat = Bone._tmpMats[0];
  70638. origLocMat.copyFrom(locMat);
  70639. var origLocMatInv = Bone._tmpMats[1];
  70640. origLocMatInv.copyFrom(origLocMat);
  70641. origLocMatInv.invert();
  70642. var scaleMat = Bone._tmpMats[2];
  70643. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  70644. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  70645. this._scaleVector.x *= x;
  70646. this._scaleVector.y *= y;
  70647. this._scaleVector.z *= z;
  70648. locMat.multiplyToRef(origLocMatInv, locMat);
  70649. locMat.multiplyToRef(scaleMat, locMat);
  70650. locMat.multiplyToRef(origLocMat, locMat);
  70651. var parent = this.getParent();
  70652. if (parent) {
  70653. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  70654. }
  70655. else {
  70656. this.getAbsoluteTransform().copyFrom(locMat);
  70657. }
  70658. var len = this.children.length;
  70659. scaleMat.invert();
  70660. for (var i = 0; i < len; i++) {
  70661. var child = this.children[i];
  70662. var cm = child.getLocalMatrix();
  70663. cm.multiplyToRef(scaleMat, cm);
  70664. var lm = child.getLocalMatrix();
  70665. lm.m[12] *= x;
  70666. lm.m[13] *= y;
  70667. lm.m[14] *= z;
  70668. }
  70669. this.computeAbsoluteTransforms();
  70670. if (scaleChildren) {
  70671. for (var i = 0; i < len; i++) {
  70672. this.children[i].scale(x, y, z, scaleChildren);
  70673. }
  70674. }
  70675. this.markAsDirty();
  70676. };
  70677. /**
  70678. * Set the yaw, pitch, and roll of the bone in local or world space.
  70679. * @param yaw The rotation of the bone on the y axis.
  70680. * @param pitch The rotation of the bone on the x axis.
  70681. * @param roll The rotation of the bone on the z axis.
  70682. * @param space The space that the axes of rotation are in.
  70683. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70684. */
  70685. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  70686. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70687. var rotMat = Bone._tmpMats[0];
  70688. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  70689. var rotMatInv = Bone._tmpMats[1];
  70690. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70691. rotMatInv.multiplyToRef(rotMat, rotMat);
  70692. this._rotateWithMatrix(rotMat, space, mesh);
  70693. };
  70694. /**
  70695. * Rotate the bone on an axis in local or world space.
  70696. * @param axis The axis to rotate the bone on.
  70697. * @param amount The amount to rotate the bone.
  70698. * @param space The space that the axis is in.
  70699. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70700. */
  70701. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  70702. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70703. var rmat = Bone._tmpMats[0];
  70704. rmat.m[12] = 0;
  70705. rmat.m[13] = 0;
  70706. rmat.m[14] = 0;
  70707. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  70708. this._rotateWithMatrix(rmat, space, mesh);
  70709. };
  70710. /**
  70711. * Set the rotation of the bone to a particular axis angle in local or world space.
  70712. * @param axis The axis to rotate the bone on.
  70713. * @param angle The angle that the bone should be rotated to.
  70714. * @param space The space that the axis is in.
  70715. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70716. */
  70717. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  70718. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70719. var rotMat = Bone._tmpMats[0];
  70720. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  70721. var rotMatInv = Bone._tmpMats[1];
  70722. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70723. rotMatInv.multiplyToRef(rotMat, rotMat);
  70724. this._rotateWithMatrix(rotMat, space, mesh);
  70725. };
  70726. /**
  70727. * Set the euler rotation of the bone in local of world space.
  70728. * @param rotation The euler rotation that the bone should be set to.
  70729. * @param space The space that the rotation is in.
  70730. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70731. */
  70732. Bone.prototype.setRotation = function (rotation, space, mesh) {
  70733. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70734. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  70735. };
  70736. /**
  70737. * Set the quaternion rotation of the bone in local of world space.
  70738. * @param quat The quaternion rotation that the bone should be set to.
  70739. * @param space The space that the rotation is in.
  70740. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70741. */
  70742. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  70743. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70744. var rotMatInv = Bone._tmpMats[0];
  70745. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70746. var rotMat = Bone._tmpMats[1];
  70747. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  70748. rotMatInv.multiplyToRef(rotMat, rotMat);
  70749. this._rotateWithMatrix(rotMat, space, mesh);
  70750. };
  70751. /**
  70752. * Set the rotation matrix of the bone in local of world space.
  70753. * @param rotMat The rotation matrix that the bone should be set to.
  70754. * @param space The space that the rotation is in.
  70755. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70756. */
  70757. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  70758. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70759. var rotMatInv = Bone._tmpMats[0];
  70760. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70761. var rotMat2 = Bone._tmpMats[1];
  70762. rotMat2.copyFrom(rotMat);
  70763. rotMatInv.multiplyToRef(rotMat, rotMat2);
  70764. this._rotateWithMatrix(rotMat2, space, mesh);
  70765. };
  70766. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  70767. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70768. var lmat = this.getLocalMatrix();
  70769. var lx = lmat.m[12];
  70770. var ly = lmat.m[13];
  70771. var lz = lmat.m[14];
  70772. var parent = this.getParent();
  70773. var parentScale = Bone._tmpMats[3];
  70774. var parentScaleInv = Bone._tmpMats[4];
  70775. if (parent) {
  70776. if (space == BABYLON.Space.WORLD) {
  70777. if (mesh) {
  70778. parentScale.copyFrom(mesh.getWorldMatrix());
  70779. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  70780. }
  70781. else {
  70782. parentScale.copyFrom(parent.getAbsoluteTransform());
  70783. }
  70784. }
  70785. else {
  70786. parentScale = parent._scaleMatrix;
  70787. }
  70788. parentScaleInv.copyFrom(parentScale);
  70789. parentScaleInv.invert();
  70790. lmat.multiplyToRef(parentScale, lmat);
  70791. lmat.multiplyToRef(rmat, lmat);
  70792. lmat.multiplyToRef(parentScaleInv, lmat);
  70793. }
  70794. else {
  70795. if (space == BABYLON.Space.WORLD && mesh) {
  70796. parentScale.copyFrom(mesh.getWorldMatrix());
  70797. parentScaleInv.copyFrom(parentScale);
  70798. parentScaleInv.invert();
  70799. lmat.multiplyToRef(parentScale, lmat);
  70800. lmat.multiplyToRef(rmat, lmat);
  70801. lmat.multiplyToRef(parentScaleInv, lmat);
  70802. }
  70803. else {
  70804. lmat.multiplyToRef(rmat, lmat);
  70805. }
  70806. }
  70807. lmat.m[12] = lx;
  70808. lmat.m[13] = ly;
  70809. lmat.m[14] = lz;
  70810. this.computeAbsoluteTransforms();
  70811. this.markAsDirty();
  70812. };
  70813. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  70814. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70815. if (space == BABYLON.Space.WORLD) {
  70816. var scaleMatrix = Bone._tmpMats[2];
  70817. scaleMatrix.copyFrom(this._scaleMatrix);
  70818. rotMatInv.copyFrom(this.getAbsoluteTransform());
  70819. if (mesh) {
  70820. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  70821. var meshScale = Bone._tmpMats[3];
  70822. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  70823. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  70824. }
  70825. rotMatInv.invert();
  70826. scaleMatrix.m[0] *= this._scalingDeterminant;
  70827. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  70828. }
  70829. else {
  70830. rotMatInv.copyFrom(this.getLocalMatrix());
  70831. rotMatInv.invert();
  70832. var scaleMatrix = Bone._tmpMats[2];
  70833. scaleMatrix.copyFrom(this._scaleMatrix);
  70834. if (this._parent) {
  70835. var pscaleMatrix = Bone._tmpMats[3];
  70836. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  70837. pscaleMatrix.invert();
  70838. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  70839. }
  70840. else {
  70841. scaleMatrix.m[0] *= this._scalingDeterminant;
  70842. }
  70843. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  70844. }
  70845. };
  70846. /**
  70847. * Get the scale of the bone
  70848. * @returns the scale of the bone
  70849. */
  70850. Bone.prototype.getScale = function () {
  70851. return this._scaleVector.clone();
  70852. };
  70853. /**
  70854. * Copy the scale of the bone to a vector3.
  70855. * @param result The vector3 to copy the scale to
  70856. */
  70857. Bone.prototype.getScaleToRef = function (result) {
  70858. result.copyFrom(this._scaleVector);
  70859. };
  70860. /**
  70861. * Get the position of the bone in local or world space.
  70862. * @param space The space that the returned position is in.
  70863. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70864. * @returns The position of the bone
  70865. */
  70866. Bone.prototype.getPosition = function (space, mesh) {
  70867. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70868. if (mesh === void 0) { mesh = null; }
  70869. var pos = BABYLON.Vector3.Zero();
  70870. this.getPositionToRef(space, mesh, pos);
  70871. return pos;
  70872. };
  70873. /**
  70874. * Copy the position of the bone to a vector3 in local or world space.
  70875. * @param space The space that the returned position is in.
  70876. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70877. * @param result The vector3 to copy the position to.
  70878. */
  70879. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  70880. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70881. if (space == BABYLON.Space.LOCAL) {
  70882. var lm = this.getLocalMatrix();
  70883. result.x = lm.m[12];
  70884. result.y = lm.m[13];
  70885. result.z = lm.m[14];
  70886. }
  70887. else {
  70888. var wm = null;
  70889. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70890. if (mesh) {
  70891. wm = mesh.getWorldMatrix();
  70892. }
  70893. this._skeleton.computeAbsoluteTransforms();
  70894. var tmat = Bone._tmpMats[0];
  70895. if (mesh && wm) {
  70896. tmat.copyFrom(this.getAbsoluteTransform());
  70897. tmat.multiplyToRef(wm, tmat);
  70898. }
  70899. else {
  70900. tmat = this.getAbsoluteTransform();
  70901. }
  70902. result.x = tmat.m[12];
  70903. result.y = tmat.m[13];
  70904. result.z = tmat.m[14];
  70905. }
  70906. };
  70907. /**
  70908. * Get the absolute position of the bone (world space).
  70909. * @param mesh The mesh that this bone is attached to.
  70910. * @returns The absolute position of the bone
  70911. */
  70912. Bone.prototype.getAbsolutePosition = function (mesh) {
  70913. if (mesh === void 0) { mesh = null; }
  70914. var pos = BABYLON.Vector3.Zero();
  70915. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  70916. return pos;
  70917. };
  70918. /**
  70919. * Copy the absolute position of the bone (world space) to the result param.
  70920. * @param mesh The mesh that this bone is attached to.
  70921. * @param result The vector3 to copy the absolute position to.
  70922. */
  70923. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  70924. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  70925. };
  70926. /**
  70927. * Compute the absolute transforms of this bone and its children.
  70928. */
  70929. Bone.prototype.computeAbsoluteTransforms = function () {
  70930. if (this._parent) {
  70931. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  70932. }
  70933. else {
  70934. this._absoluteTransform.copyFrom(this._localMatrix);
  70935. var poseMatrix = this._skeleton.getPoseMatrix();
  70936. if (poseMatrix) {
  70937. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  70938. }
  70939. }
  70940. var children = this.children;
  70941. var len = children.length;
  70942. for (var i = 0; i < len; i++) {
  70943. children[i].computeAbsoluteTransforms();
  70944. }
  70945. };
  70946. Bone.prototype._syncScaleVector = function () {
  70947. var lm = this.getLocalMatrix();
  70948. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  70949. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  70950. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  70951. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  70952. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  70953. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  70954. this._scaleVector.x = xs * Math.sqrt(xsq);
  70955. this._scaleVector.y = ys * Math.sqrt(ysq);
  70956. this._scaleVector.z = zs * Math.sqrt(zsq);
  70957. if (this._parent) {
  70958. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  70959. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  70960. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  70961. }
  70962. 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);
  70963. };
  70964. /**
  70965. * Get the world direction from an axis that is in the local space of the bone.
  70966. * @param localAxis The local direction that is used to compute the world direction.
  70967. * @param mesh The mesh that this bone is attached to.
  70968. * @returns The world direction
  70969. */
  70970. Bone.prototype.getDirection = function (localAxis, mesh) {
  70971. if (mesh === void 0) { mesh = null; }
  70972. var result = BABYLON.Vector3.Zero();
  70973. this.getDirectionToRef(localAxis, mesh, result);
  70974. return result;
  70975. };
  70976. /**
  70977. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  70978. * @param localAxis The local direction that is used to compute the world direction.
  70979. * @param mesh The mesh that this bone is attached to.
  70980. * @param result The vector3 that the world direction will be copied to.
  70981. */
  70982. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  70983. if (mesh === void 0) { mesh = null; }
  70984. var wm = null;
  70985. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70986. if (mesh) {
  70987. wm = mesh.getWorldMatrix();
  70988. }
  70989. this._skeleton.computeAbsoluteTransforms();
  70990. var mat = Bone._tmpMats[0];
  70991. mat.copyFrom(this.getAbsoluteTransform());
  70992. if (mesh && wm) {
  70993. mat.multiplyToRef(wm, mat);
  70994. }
  70995. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  70996. result.normalize();
  70997. };
  70998. /**
  70999. * Get the euler rotation of the bone in local or world space.
  71000. * @param space The space that the rotation should be in.
  71001. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71002. * @returns The euler rotation
  71003. */
  71004. Bone.prototype.getRotation = function (space, mesh) {
  71005. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71006. if (mesh === void 0) { mesh = null; }
  71007. var result = BABYLON.Vector3.Zero();
  71008. this.getRotationToRef(space, mesh, result);
  71009. return result;
  71010. };
  71011. /**
  71012. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  71013. * @param space The space that the rotation should be in.
  71014. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71015. * @param result The vector3 that the rotation should be copied to.
  71016. */
  71017. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  71018. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71019. if (mesh === void 0) { mesh = null; }
  71020. var quat = Bone._tmpQuat;
  71021. this.getRotationQuaternionToRef(space, mesh, quat);
  71022. quat.toEulerAnglesToRef(result);
  71023. };
  71024. /**
  71025. * Get the quaternion rotation of the bone in either local or world space.
  71026. * @param space The space that the rotation should be in.
  71027. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71028. * @returns The quaternion rotation
  71029. */
  71030. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  71031. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71032. if (mesh === void 0) { mesh = null; }
  71033. var result = BABYLON.Quaternion.Identity();
  71034. this.getRotationQuaternionToRef(space, mesh, result);
  71035. return result;
  71036. };
  71037. /**
  71038. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  71039. * @param space The space that the rotation should be in.
  71040. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71041. * @param result The quaternion that the rotation should be copied to.
  71042. */
  71043. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  71044. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71045. if (mesh === void 0) { mesh = null; }
  71046. if (space == BABYLON.Space.LOCAL) {
  71047. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  71048. }
  71049. else {
  71050. var mat = Bone._tmpMats[0];
  71051. var amat = this.getAbsoluteTransform();
  71052. if (mesh) {
  71053. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  71054. }
  71055. else {
  71056. mat.copyFrom(amat);
  71057. }
  71058. mat.m[0] *= this._scalingDeterminant;
  71059. mat.m[1] *= this._scalingDeterminant;
  71060. mat.m[2] *= this._scalingDeterminant;
  71061. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  71062. }
  71063. };
  71064. /**
  71065. * Get the rotation matrix of the bone in local or world space.
  71066. * @param space The space that the rotation should be in.
  71067. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71068. * @returns The rotation matrix
  71069. */
  71070. Bone.prototype.getRotationMatrix = function (space, mesh) {
  71071. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71072. var result = BABYLON.Matrix.Identity();
  71073. this.getRotationMatrixToRef(space, mesh, result);
  71074. return result;
  71075. };
  71076. /**
  71077. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  71078. * @param space The space that the rotation should be in.
  71079. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71080. * @param result The quaternion that the rotation should be copied to.
  71081. */
  71082. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  71083. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71084. if (space == BABYLON.Space.LOCAL) {
  71085. this.getLocalMatrix().getRotationMatrixToRef(result);
  71086. }
  71087. else {
  71088. var mat = Bone._tmpMats[0];
  71089. var amat = this.getAbsoluteTransform();
  71090. if (mesh) {
  71091. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  71092. }
  71093. else {
  71094. mat.copyFrom(amat);
  71095. }
  71096. mat.m[0] *= this._scalingDeterminant;
  71097. mat.m[1] *= this._scalingDeterminant;
  71098. mat.m[2] *= this._scalingDeterminant;
  71099. mat.getRotationMatrixToRef(result);
  71100. }
  71101. };
  71102. /**
  71103. * Get the world position of a point that is in the local space of the bone.
  71104. * @param position The local position
  71105. * @param mesh The mesh that this bone is attached to.
  71106. * @returns The world position
  71107. */
  71108. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  71109. if (mesh === void 0) { mesh = null; }
  71110. var result = BABYLON.Vector3.Zero();
  71111. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  71112. return result;
  71113. };
  71114. /**
  71115. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  71116. * @param position The local position
  71117. * @param mesh The mesh that this bone is attached to.
  71118. * @param result The vector3 that the world position should be copied to.
  71119. */
  71120. Bone.prototype.getAbsolutePositionFromLocalToRef = 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. if (mesh && wm) {
  71130. tmat.copyFrom(this.getAbsoluteTransform());
  71131. tmat.multiplyToRef(wm, tmat);
  71132. }
  71133. else {
  71134. tmat = this.getAbsoluteTransform();
  71135. }
  71136. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  71137. };
  71138. /**
  71139. * Get the local position of a point that is in world space.
  71140. * @param position The world position
  71141. * @param mesh The mesh that this bone is attached to.
  71142. * @returns The local position
  71143. */
  71144. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  71145. if (mesh === void 0) { mesh = null; }
  71146. var result = BABYLON.Vector3.Zero();
  71147. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  71148. return result;
  71149. };
  71150. /**
  71151. * Get the local position of a point that is in world space and copy it to the result param.
  71152. * @param position The world position
  71153. * @param mesh The mesh that this bone is attached to.
  71154. * @param result The vector3 that the local position should be copied to.
  71155. */
  71156. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  71157. if (mesh === void 0) { mesh = null; }
  71158. var wm = null;
  71159. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71160. if (mesh) {
  71161. wm = mesh.getWorldMatrix();
  71162. }
  71163. this._skeleton.computeAbsoluteTransforms();
  71164. var tmat = Bone._tmpMats[0];
  71165. tmat.copyFrom(this.getAbsoluteTransform());
  71166. if (mesh && wm) {
  71167. tmat.multiplyToRef(wm, tmat);
  71168. }
  71169. tmat.invert();
  71170. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  71171. };
  71172. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71173. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  71174. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  71175. return Bone;
  71176. }(BABYLON.Node));
  71177. BABYLON.Bone = Bone;
  71178. })(BABYLON || (BABYLON = {}));
  71179. //# sourceMappingURL=babylon.bone.js.map
  71180. var BABYLON;
  71181. (function (BABYLON) {
  71182. var BoneIKController = /** @class */ (function () {
  71183. function BoneIKController(mesh, bone, options) {
  71184. this.targetPosition = BABYLON.Vector3.Zero();
  71185. this.poleTargetPosition = BABYLON.Vector3.Zero();
  71186. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  71187. this.poleAngle = 0;
  71188. this.slerpAmount = 1;
  71189. this._bone1Quat = BABYLON.Quaternion.Identity();
  71190. this._bone1Mat = BABYLON.Matrix.Identity();
  71191. this._bone2Ang = Math.PI;
  71192. this._maxAngle = Math.PI;
  71193. this._rightHandedSystem = false;
  71194. this._bendAxis = BABYLON.Vector3.Right();
  71195. this._slerping = false;
  71196. this._adjustRoll = 0;
  71197. this._bone2 = bone;
  71198. this._bone1 = bone.getParent();
  71199. if (!this._bone1) {
  71200. return;
  71201. }
  71202. this.mesh = mesh;
  71203. var bonePos = bone.getPosition();
  71204. if (bone.getAbsoluteTransform().determinant() > 0) {
  71205. this._rightHandedSystem = true;
  71206. this._bendAxis.x = 0;
  71207. this._bendAxis.y = 0;
  71208. this._bendAxis.z = -1;
  71209. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  71210. this._adjustRoll = Math.PI * .5;
  71211. this._bendAxis.z = 1;
  71212. }
  71213. }
  71214. if (this._bone1.length) {
  71215. var boneScale1 = this._bone1.getScale();
  71216. var boneScale2 = this._bone2.getScale();
  71217. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  71218. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  71219. }
  71220. else if (this._bone1.children[0]) {
  71221. mesh.computeWorldMatrix(true);
  71222. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  71223. var pos2 = this._bone2.getAbsolutePosition(mesh);
  71224. var pos3 = this._bone1.getAbsolutePosition(mesh);
  71225. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  71226. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  71227. }
  71228. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  71229. this.maxAngle = Math.PI;
  71230. if (options) {
  71231. if (options.targetMesh) {
  71232. this.targetMesh = options.targetMesh;
  71233. this.targetMesh.computeWorldMatrix(true);
  71234. }
  71235. if (options.poleTargetMesh) {
  71236. this.poleTargetMesh = options.poleTargetMesh;
  71237. this.poleTargetMesh.computeWorldMatrix(true);
  71238. }
  71239. else if (options.poleTargetBone) {
  71240. this.poleTargetBone = options.poleTargetBone;
  71241. }
  71242. else if (this._bone1.getParent()) {
  71243. this.poleTargetBone = this._bone1.getParent();
  71244. }
  71245. if (options.poleTargetLocalOffset) {
  71246. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  71247. }
  71248. if (options.poleAngle) {
  71249. this.poleAngle = options.poleAngle;
  71250. }
  71251. if (options.bendAxis) {
  71252. this._bendAxis.copyFrom(options.bendAxis);
  71253. }
  71254. if (options.maxAngle) {
  71255. this.maxAngle = options.maxAngle;
  71256. }
  71257. if (options.slerpAmount) {
  71258. this.slerpAmount = options.slerpAmount;
  71259. }
  71260. }
  71261. }
  71262. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  71263. get: function () {
  71264. return this._maxAngle;
  71265. },
  71266. set: function (value) {
  71267. this._setMaxAngle(value);
  71268. },
  71269. enumerable: true,
  71270. configurable: true
  71271. });
  71272. BoneIKController.prototype._setMaxAngle = function (ang) {
  71273. if (ang < 0) {
  71274. ang = 0;
  71275. }
  71276. if (ang > Math.PI || ang == undefined) {
  71277. ang = Math.PI;
  71278. }
  71279. this._maxAngle = ang;
  71280. var a = this._bone1Length;
  71281. var b = this._bone2Length;
  71282. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  71283. };
  71284. BoneIKController.prototype.update = function () {
  71285. var bone1 = this._bone1;
  71286. if (!bone1) {
  71287. return;
  71288. }
  71289. var target = this.targetPosition;
  71290. var poleTarget = this.poleTargetPosition;
  71291. var mat1 = BoneIKController._tmpMats[0];
  71292. var mat2 = BoneIKController._tmpMats[1];
  71293. if (this.targetMesh) {
  71294. target.copyFrom(this.targetMesh.getAbsolutePosition());
  71295. }
  71296. if (this.poleTargetBone) {
  71297. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  71298. }
  71299. else if (this.poleTargetMesh) {
  71300. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  71301. }
  71302. var bonePos = BoneIKController._tmpVecs[0];
  71303. var zaxis = BoneIKController._tmpVecs[1];
  71304. var xaxis = BoneIKController._tmpVecs[2];
  71305. var yaxis = BoneIKController._tmpVecs[3];
  71306. var upAxis = BoneIKController._tmpVecs[4];
  71307. var _tmpQuat = BoneIKController._tmpQuat;
  71308. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  71309. poleTarget.subtractToRef(bonePos, upAxis);
  71310. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  71311. upAxis.y = 1;
  71312. }
  71313. else {
  71314. upAxis.normalize();
  71315. }
  71316. target.subtractToRef(bonePos, yaxis);
  71317. yaxis.normalize();
  71318. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  71319. zaxis.normalize();
  71320. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  71321. xaxis.normalize();
  71322. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  71323. var a = this._bone1Length;
  71324. var b = this._bone2Length;
  71325. var c = BABYLON.Vector3.Distance(bonePos, target);
  71326. if (this._maxReach > 0) {
  71327. c = Math.min(this._maxReach, c);
  71328. }
  71329. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  71330. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  71331. if (acosa > 1) {
  71332. acosa = 1;
  71333. }
  71334. if (acosb > 1) {
  71335. acosb = 1;
  71336. }
  71337. if (acosa < -1) {
  71338. acosa = -1;
  71339. }
  71340. if (acosb < -1) {
  71341. acosb = -1;
  71342. }
  71343. var angA = Math.acos(acosa);
  71344. var angB = Math.acos(acosb);
  71345. var angC = -angA - angB;
  71346. if (this._rightHandedSystem) {
  71347. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  71348. mat2.multiplyToRef(mat1, mat1);
  71349. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  71350. mat2.multiplyToRef(mat1, mat1);
  71351. }
  71352. else {
  71353. var _tmpVec = BoneIKController._tmpVecs[5];
  71354. _tmpVec.copyFrom(this._bendAxis);
  71355. _tmpVec.x *= -1;
  71356. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  71357. mat2.multiplyToRef(mat1, mat1);
  71358. }
  71359. if (this.poleAngle) {
  71360. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  71361. mat1.multiplyToRef(mat2, mat1);
  71362. }
  71363. if (this._bone1) {
  71364. if (this.slerpAmount < 1) {
  71365. if (!this._slerping) {
  71366. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  71367. }
  71368. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  71369. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  71370. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  71371. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  71372. this._slerping = true;
  71373. }
  71374. else {
  71375. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  71376. this._bone1Mat.copyFrom(mat1);
  71377. this._slerping = false;
  71378. }
  71379. }
  71380. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  71381. this._bone2Ang = angC;
  71382. };
  71383. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71384. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  71385. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  71386. return BoneIKController;
  71387. }());
  71388. BABYLON.BoneIKController = BoneIKController;
  71389. })(BABYLON || (BABYLON = {}));
  71390. //# sourceMappingURL=babylon.boneIKController.js.map
  71391. var BABYLON;
  71392. (function (BABYLON) {
  71393. var BoneLookController = /** @class */ (function () {
  71394. /**
  71395. * Create a BoneLookController
  71396. * @param mesh the mesh that the bone belongs to
  71397. * @param bone the bone that will be looking to the target
  71398. * @param target the target Vector3 to look at
  71399. * @param settings optional settings:
  71400. * - maxYaw: the maximum angle the bone will yaw to
  71401. * - minYaw: the minimum angle the bone will yaw to
  71402. * - maxPitch: the maximum angle the bone will pitch to
  71403. * - minPitch: the minimum angle the bone will yaw to
  71404. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  71405. * - upAxis: the up axis of the coordinate system
  71406. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  71407. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  71408. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  71409. * - adjustYaw: used to make an adjustment to the yaw of the bone
  71410. * - adjustPitch: used to make an adjustment to the pitch of the bone
  71411. * - adjustRoll: used to make an adjustment to the roll of the bone
  71412. **/
  71413. function BoneLookController(mesh, bone, target, options) {
  71414. /**
  71415. * The up axis of the coordinate system that is used when the bone is rotated.
  71416. */
  71417. this.upAxis = BABYLON.Vector3.Up();
  71418. /**
  71419. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  71420. */
  71421. this.upAxisSpace = BABYLON.Space.LOCAL;
  71422. /**
  71423. * Used to make an adjustment to the yaw of the bone.
  71424. */
  71425. this.adjustYaw = 0;
  71426. /**
  71427. * Used to make an adjustment to the pitch of the bone.
  71428. */
  71429. this.adjustPitch = 0;
  71430. /**
  71431. * Used to make an adjustment to the roll of the bone.
  71432. */
  71433. this.adjustRoll = 0;
  71434. /**
  71435. * 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).
  71436. */
  71437. this.slerpAmount = 1;
  71438. this._boneQuat = BABYLON.Quaternion.Identity();
  71439. this._slerping = false;
  71440. this._firstFrameSkipped = false;
  71441. this._fowardAxis = BABYLON.Vector3.Forward();
  71442. this.mesh = mesh;
  71443. this.bone = bone;
  71444. this.target = target;
  71445. if (options) {
  71446. if (options.adjustYaw) {
  71447. this.adjustYaw = options.adjustYaw;
  71448. }
  71449. if (options.adjustPitch) {
  71450. this.adjustPitch = options.adjustPitch;
  71451. }
  71452. if (options.adjustRoll) {
  71453. this.adjustRoll = options.adjustRoll;
  71454. }
  71455. if (options.maxYaw != null) {
  71456. this.maxYaw = options.maxYaw;
  71457. }
  71458. else {
  71459. this.maxYaw = Math.PI;
  71460. }
  71461. if (options.minYaw != null) {
  71462. this.minYaw = options.minYaw;
  71463. }
  71464. else {
  71465. this.minYaw = -Math.PI;
  71466. }
  71467. if (options.maxPitch != null) {
  71468. this.maxPitch = options.maxPitch;
  71469. }
  71470. else {
  71471. this.maxPitch = Math.PI;
  71472. }
  71473. if (options.minPitch != null) {
  71474. this.minPitch = options.minPitch;
  71475. }
  71476. else {
  71477. this.minPitch = -Math.PI;
  71478. }
  71479. if (options.slerpAmount != null) {
  71480. this.slerpAmount = options.slerpAmount;
  71481. }
  71482. if (options.upAxis != null) {
  71483. this.upAxis = options.upAxis;
  71484. }
  71485. if (options.upAxisSpace != null) {
  71486. this.upAxisSpace = options.upAxisSpace;
  71487. }
  71488. if (options.yawAxis != null || options.pitchAxis != null) {
  71489. var newYawAxis = BABYLON.Axis.Y;
  71490. var newPitchAxis = BABYLON.Axis.X;
  71491. if (options.yawAxis != null) {
  71492. newYawAxis = options.yawAxis.clone();
  71493. newYawAxis.normalize();
  71494. }
  71495. if (options.pitchAxis != null) {
  71496. newPitchAxis = options.pitchAxis.clone();
  71497. newPitchAxis.normalize();
  71498. }
  71499. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  71500. this._transformYawPitch = BABYLON.Matrix.Identity();
  71501. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  71502. this._transformYawPitchInv = this._transformYawPitch.clone();
  71503. this._transformYawPitch.invert();
  71504. }
  71505. }
  71506. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  71507. this.upAxisSpace = BABYLON.Space.LOCAL;
  71508. }
  71509. }
  71510. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  71511. /**
  71512. * Get/set the minimum yaw angle that the bone can look to.
  71513. */
  71514. get: function () {
  71515. return this._minYaw;
  71516. },
  71517. set: function (value) {
  71518. this._minYaw = value;
  71519. this._minYawSin = Math.sin(value);
  71520. this._minYawCos = Math.cos(value);
  71521. if (this._maxYaw != null) {
  71522. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  71523. this._yawRange = this._maxYaw - this._minYaw;
  71524. }
  71525. },
  71526. enumerable: true,
  71527. configurable: true
  71528. });
  71529. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  71530. /**
  71531. * Get/set the maximum yaw angle that the bone can look to.
  71532. */
  71533. get: function () {
  71534. return this._maxYaw;
  71535. },
  71536. set: function (value) {
  71537. this._maxYaw = value;
  71538. this._maxYawSin = Math.sin(value);
  71539. this._maxYawCos = Math.cos(value);
  71540. if (this._minYaw != null) {
  71541. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  71542. this._yawRange = this._maxYaw - this._minYaw;
  71543. }
  71544. },
  71545. enumerable: true,
  71546. configurable: true
  71547. });
  71548. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  71549. /**
  71550. * Get/set the minimum pitch angle that the bone can look to.
  71551. */
  71552. get: function () {
  71553. return this._minPitch;
  71554. },
  71555. set: function (value) {
  71556. this._minPitch = value;
  71557. this._minPitchTan = Math.tan(value);
  71558. },
  71559. enumerable: true,
  71560. configurable: true
  71561. });
  71562. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  71563. /**
  71564. * Get/set the maximum pitch angle that the bone can look to.
  71565. */
  71566. get: function () {
  71567. return this._maxPitch;
  71568. },
  71569. set: function (value) {
  71570. this._maxPitch = value;
  71571. this._maxPitchTan = Math.tan(value);
  71572. },
  71573. enumerable: true,
  71574. configurable: true
  71575. });
  71576. /**
  71577. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  71578. */
  71579. BoneLookController.prototype.update = function () {
  71580. //skip the first frame when slerping so that the mesh rotation is correct
  71581. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  71582. this._firstFrameSkipped = true;
  71583. return;
  71584. }
  71585. var bone = this.bone;
  71586. var bonePos = BoneLookController._tmpVecs[0];
  71587. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  71588. var target = this.target;
  71589. var _tmpMat1 = BoneLookController._tmpMats[0];
  71590. var _tmpMat2 = BoneLookController._tmpMats[1];
  71591. var mesh = this.mesh;
  71592. var parentBone = bone.getParent();
  71593. var upAxis = BoneLookController._tmpVecs[1];
  71594. upAxis.copyFrom(this.upAxis);
  71595. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  71596. if (this._transformYawPitch) {
  71597. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  71598. }
  71599. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  71600. }
  71601. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  71602. mesh.getDirectionToRef(upAxis, upAxis);
  71603. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  71604. upAxis.normalize();
  71605. }
  71606. }
  71607. var checkYaw = false;
  71608. var checkPitch = false;
  71609. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  71610. checkYaw = true;
  71611. }
  71612. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  71613. checkPitch = true;
  71614. }
  71615. if (checkYaw || checkPitch) {
  71616. var spaceMat = BoneLookController._tmpMats[2];
  71617. var spaceMatInv = BoneLookController._tmpMats[3];
  71618. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  71619. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  71620. }
  71621. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  71622. spaceMat.copyFrom(mesh.getWorldMatrix());
  71623. }
  71624. else {
  71625. var forwardAxis = BoneLookController._tmpVecs[2];
  71626. forwardAxis.copyFrom(this._fowardAxis);
  71627. if (this._transformYawPitch) {
  71628. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  71629. }
  71630. if (parentBone) {
  71631. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  71632. }
  71633. else {
  71634. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  71635. }
  71636. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  71637. rightAxis.normalize();
  71638. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  71639. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  71640. }
  71641. spaceMat.invertToRef(spaceMatInv);
  71642. var xzlen = null;
  71643. if (checkPitch) {
  71644. var localTarget = BoneLookController._tmpVecs[3];
  71645. target.subtractToRef(bonePos, localTarget);
  71646. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  71647. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71648. var pitch = Math.atan2(localTarget.y, xzlen);
  71649. var newPitch = pitch;
  71650. if (pitch > this._maxPitch) {
  71651. localTarget.y = this._maxPitchTan * xzlen;
  71652. newPitch = this._maxPitch;
  71653. }
  71654. else if (pitch < this._minPitch) {
  71655. localTarget.y = this._minPitchTan * xzlen;
  71656. newPitch = this._minPitch;
  71657. }
  71658. if (pitch != newPitch) {
  71659. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  71660. localTarget.addInPlace(bonePos);
  71661. target = localTarget;
  71662. }
  71663. }
  71664. if (checkYaw) {
  71665. var localTarget = BoneLookController._tmpVecs[4];
  71666. target.subtractToRef(bonePos, localTarget);
  71667. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  71668. var yaw = Math.atan2(localTarget.x, localTarget.z);
  71669. var newYaw = yaw;
  71670. if (yaw > this._maxYaw || yaw < this._minYaw) {
  71671. if (xzlen == null) {
  71672. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71673. }
  71674. if (this._yawRange > Math.PI) {
  71675. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  71676. localTarget.z = this._maxYawCos * xzlen;
  71677. localTarget.x = this._maxYawSin * xzlen;
  71678. newYaw = this._maxYaw;
  71679. }
  71680. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  71681. localTarget.z = this._minYawCos * xzlen;
  71682. localTarget.x = this._minYawSin * xzlen;
  71683. newYaw = this._minYaw;
  71684. }
  71685. }
  71686. else {
  71687. if (yaw > this._maxYaw) {
  71688. localTarget.z = this._maxYawCos * xzlen;
  71689. localTarget.x = this._maxYawSin * xzlen;
  71690. newYaw = this._maxYaw;
  71691. }
  71692. else if (yaw < this._minYaw) {
  71693. localTarget.z = this._minYawCos * xzlen;
  71694. localTarget.x = this._minYawSin * xzlen;
  71695. newYaw = this._minYaw;
  71696. }
  71697. }
  71698. }
  71699. if (this._slerping && this._yawRange > Math.PI) {
  71700. //are we going to be crossing into the min/max region?
  71701. var boneFwd = BoneLookController._tmpVecs[8];
  71702. boneFwd.copyFrom(BABYLON.Axis.Z);
  71703. if (this._transformYawPitch) {
  71704. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  71705. }
  71706. var boneRotMat = BoneLookController._tmpMats[4];
  71707. this._boneQuat.toRotationMatrix(boneRotMat);
  71708. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  71709. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  71710. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  71711. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  71712. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  71713. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  71714. if (angBtwTar > angBtwMidYaw) {
  71715. if (xzlen == null) {
  71716. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71717. }
  71718. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  71719. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  71720. if (angBtwMin < angBtwMax) {
  71721. newYaw = boneYaw + Math.PI * .75;
  71722. localTarget.z = Math.cos(newYaw) * xzlen;
  71723. localTarget.x = Math.sin(newYaw) * xzlen;
  71724. }
  71725. else {
  71726. newYaw = boneYaw - Math.PI * .75;
  71727. localTarget.z = Math.cos(newYaw) * xzlen;
  71728. localTarget.x = Math.sin(newYaw) * xzlen;
  71729. }
  71730. }
  71731. }
  71732. if (yaw != newYaw) {
  71733. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  71734. localTarget.addInPlace(bonePos);
  71735. target = localTarget;
  71736. }
  71737. }
  71738. }
  71739. var zaxis = BoneLookController._tmpVecs[5];
  71740. var xaxis = BoneLookController._tmpVecs[6];
  71741. var yaxis = BoneLookController._tmpVecs[7];
  71742. var _tmpQuat = BoneLookController._tmpQuat;
  71743. target.subtractToRef(bonePos, zaxis);
  71744. zaxis.normalize();
  71745. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  71746. xaxis.normalize();
  71747. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  71748. yaxis.normalize();
  71749. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  71750. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  71751. return;
  71752. }
  71753. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  71754. return;
  71755. }
  71756. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  71757. return;
  71758. }
  71759. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  71760. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  71761. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  71762. }
  71763. if (this.slerpAmount < 1) {
  71764. if (!this._slerping) {
  71765. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  71766. }
  71767. if (this._transformYawPitch) {
  71768. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  71769. }
  71770. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  71771. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  71772. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  71773. this._slerping = true;
  71774. }
  71775. else {
  71776. if (this._transformYawPitch) {
  71777. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  71778. }
  71779. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  71780. this._slerping = false;
  71781. }
  71782. };
  71783. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  71784. var angDiff = ang2 - ang1;
  71785. angDiff %= Math.PI * 2;
  71786. if (angDiff > Math.PI) {
  71787. angDiff -= Math.PI * 2;
  71788. }
  71789. else if (angDiff < -Math.PI) {
  71790. angDiff += Math.PI * 2;
  71791. }
  71792. return angDiff;
  71793. };
  71794. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  71795. ang1 %= (2 * Math.PI);
  71796. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  71797. ang2 %= (2 * Math.PI);
  71798. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  71799. var ab = 0;
  71800. if (ang1 < ang2) {
  71801. ab = ang2 - ang1;
  71802. }
  71803. else {
  71804. ab = ang1 - ang2;
  71805. }
  71806. if (ab > Math.PI) {
  71807. ab = Math.PI * 2 - ab;
  71808. }
  71809. return ab;
  71810. };
  71811. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  71812. ang %= (2 * Math.PI);
  71813. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  71814. ang1 %= (2 * Math.PI);
  71815. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  71816. ang2 %= (2 * Math.PI);
  71817. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  71818. if (ang1 < ang2) {
  71819. if (ang > ang1 && ang < ang2) {
  71820. return true;
  71821. }
  71822. }
  71823. else {
  71824. if (ang > ang2 && ang < ang1) {
  71825. return true;
  71826. }
  71827. }
  71828. return false;
  71829. };
  71830. 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()];
  71831. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  71832. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  71833. return BoneLookController;
  71834. }());
  71835. BABYLON.BoneLookController = BoneLookController;
  71836. })(BABYLON || (BABYLON = {}));
  71837. //# sourceMappingURL=babylon.boneLookController.js.map
  71838. var BABYLON;
  71839. (function (BABYLON) {
  71840. var Skeleton = /** @class */ (function () {
  71841. function Skeleton(name, id, scene) {
  71842. this.name = name;
  71843. this.id = id;
  71844. this.bones = new Array();
  71845. this.needInitialSkinMatrix = false;
  71846. this._isDirty = true;
  71847. this._meshesWithPoseMatrix = new Array();
  71848. this._identity = BABYLON.Matrix.Identity();
  71849. this._ranges = {};
  71850. this._lastAbsoluteTransformsUpdateId = -1;
  71851. /**
  71852. * Specifies if the skeleton should be serialized.
  71853. */
  71854. this.doNotSerialize = false;
  71855. // Events
  71856. /**
  71857. * An event triggered before computing the skeleton's matrices
  71858. * @type {BABYLON.Observable}
  71859. */
  71860. this.onBeforeComputeObservable = new BABYLON.Observable();
  71861. this.bones = [];
  71862. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  71863. scene.skeletons.push(this);
  71864. //make sure it will recalculate the matrix next time prepare is called.
  71865. this._isDirty = true;
  71866. }
  71867. // Members
  71868. Skeleton.prototype.getTransformMatrices = function (mesh) {
  71869. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  71870. return mesh._bonesTransformMatrices;
  71871. }
  71872. if (!this._transformMatrices) {
  71873. this.prepare();
  71874. }
  71875. return this._transformMatrices;
  71876. };
  71877. Skeleton.prototype.getScene = function () {
  71878. return this._scene;
  71879. };
  71880. // Methods
  71881. /**
  71882. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  71883. */
  71884. Skeleton.prototype.toString = function (fullDetails) {
  71885. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  71886. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  71887. if (fullDetails) {
  71888. ret += ", Ranges: {";
  71889. var first = true;
  71890. for (var name_1 in this._ranges) {
  71891. if (first) {
  71892. ret += ", ";
  71893. first = false;
  71894. }
  71895. ret += name_1;
  71896. }
  71897. ret += "}";
  71898. }
  71899. return ret;
  71900. };
  71901. /**
  71902. * Get bone's index searching by name
  71903. * @param {string} name is bone's name to search for
  71904. * @return {number} Indice of the bone. Returns -1 if not found
  71905. */
  71906. Skeleton.prototype.getBoneIndexByName = function (name) {
  71907. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  71908. if (this.bones[boneIndex].name === name) {
  71909. return boneIndex;
  71910. }
  71911. }
  71912. return -1;
  71913. };
  71914. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  71915. // check name not already in use
  71916. if (!this._ranges[name]) {
  71917. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  71918. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  71919. if (this.bones[i].animations[0]) {
  71920. this.bones[i].animations[0].createRange(name, from, to);
  71921. }
  71922. }
  71923. }
  71924. };
  71925. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  71926. if (deleteFrames === void 0) { deleteFrames = true; }
  71927. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  71928. if (this.bones[i].animations[0]) {
  71929. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  71930. }
  71931. }
  71932. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  71933. };
  71934. Skeleton.prototype.getAnimationRange = function (name) {
  71935. return this._ranges[name];
  71936. };
  71937. /**
  71938. * Returns as an Array, all AnimationRanges defined on this skeleton
  71939. */
  71940. Skeleton.prototype.getAnimationRanges = function () {
  71941. var animationRanges = [];
  71942. var name;
  71943. var i = 0;
  71944. for (name in this._ranges) {
  71945. animationRanges[i] = this._ranges[name];
  71946. i++;
  71947. }
  71948. return animationRanges;
  71949. };
  71950. /**
  71951. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  71952. */
  71953. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  71954. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  71955. if (this._ranges[name] || !source.getAnimationRange(name)) {
  71956. return false;
  71957. }
  71958. var ret = true;
  71959. var frameOffset = this._getHighestAnimationFrame() + 1;
  71960. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  71961. var boneDict = {};
  71962. var sourceBones = source.bones;
  71963. var nBones;
  71964. var i;
  71965. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  71966. boneDict[sourceBones[i].name] = sourceBones[i];
  71967. }
  71968. if (this.bones.length !== sourceBones.length) {
  71969. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  71970. ret = false;
  71971. }
  71972. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  71973. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  71974. var boneName = this.bones[i].name;
  71975. var sourceBone = boneDict[boneName];
  71976. if (sourceBone) {
  71977. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  71978. }
  71979. else {
  71980. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  71981. ret = false;
  71982. }
  71983. }
  71984. // do not call createAnimationRange(), since it also is done to bones, which was already done
  71985. var range = source.getAnimationRange(name);
  71986. if (range) {
  71987. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  71988. }
  71989. return ret;
  71990. };
  71991. Skeleton.prototype.returnToRest = function () {
  71992. for (var index = 0; index < this.bones.length; index++) {
  71993. this.bones[index].returnToRest();
  71994. }
  71995. };
  71996. Skeleton.prototype._getHighestAnimationFrame = function () {
  71997. var ret = 0;
  71998. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  71999. if (this.bones[i].animations[0]) {
  72000. var highest = this.bones[i].animations[0].getHighestFrame();
  72001. if (ret < highest) {
  72002. ret = highest;
  72003. }
  72004. }
  72005. }
  72006. return ret;
  72007. };
  72008. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  72009. var range = this.getAnimationRange(name);
  72010. if (!range) {
  72011. return null;
  72012. }
  72013. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  72014. };
  72015. Skeleton.prototype._markAsDirty = function () {
  72016. this._isDirty = true;
  72017. };
  72018. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  72019. this._meshesWithPoseMatrix.push(mesh);
  72020. };
  72021. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  72022. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  72023. if (index > -1) {
  72024. this._meshesWithPoseMatrix.splice(index, 1);
  72025. }
  72026. };
  72027. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  72028. this.onBeforeComputeObservable.notifyObservers(this);
  72029. for (var index = 0; index < this.bones.length; index++) {
  72030. var bone = this.bones[index];
  72031. var parentBone = bone.getParent();
  72032. if (parentBone) {
  72033. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  72034. }
  72035. else {
  72036. if (initialSkinMatrix) {
  72037. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  72038. }
  72039. else {
  72040. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  72041. }
  72042. }
  72043. if (bone._index !== -1) {
  72044. var mappedIndex = bone._index === null ? index : bone._index;
  72045. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  72046. }
  72047. }
  72048. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  72049. };
  72050. Skeleton.prototype.prepare = function () {
  72051. if (!this._isDirty) {
  72052. return;
  72053. }
  72054. if (this.needInitialSkinMatrix) {
  72055. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  72056. var mesh = this._meshesWithPoseMatrix[index];
  72057. var poseMatrix = mesh.getPoseMatrix();
  72058. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  72059. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  72060. }
  72061. if (this._synchronizedWithMesh !== mesh) {
  72062. this._synchronizedWithMesh = mesh;
  72063. // Prepare bones
  72064. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  72065. var bone = this.bones[boneIndex];
  72066. if (!bone.getParent()) {
  72067. var matrix = bone.getBaseMatrix();
  72068. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  72069. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  72070. }
  72071. }
  72072. }
  72073. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  72074. }
  72075. }
  72076. else {
  72077. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  72078. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  72079. }
  72080. this._computeTransformMatrices(this._transformMatrices, null);
  72081. }
  72082. this._isDirty = false;
  72083. this._scene._activeBones.addCount(this.bones.length, false);
  72084. };
  72085. Skeleton.prototype.getAnimatables = function () {
  72086. if (!this._animatables || this._animatables.length !== this.bones.length) {
  72087. this._animatables = [];
  72088. for (var index = 0; index < this.bones.length; index++) {
  72089. this._animatables.push(this.bones[index]);
  72090. }
  72091. }
  72092. return this._animatables;
  72093. };
  72094. Skeleton.prototype.clone = function (name, id) {
  72095. var result = new Skeleton(name, id || name, this._scene);
  72096. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  72097. for (var index = 0; index < this.bones.length; index++) {
  72098. var source = this.bones[index];
  72099. var parentBone = null;
  72100. var parent_1 = source.getParent();
  72101. if (parent_1) {
  72102. var parentIndex = this.bones.indexOf(parent_1);
  72103. parentBone = result.bones[parentIndex];
  72104. }
  72105. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  72106. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  72107. }
  72108. if (this._ranges) {
  72109. result._ranges = {};
  72110. for (var rangeName in this._ranges) {
  72111. var range = this._ranges[rangeName];
  72112. if (range) {
  72113. result._ranges[rangeName] = range.clone();
  72114. }
  72115. }
  72116. }
  72117. this._isDirty = true;
  72118. return result;
  72119. };
  72120. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  72121. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  72122. this.bones.forEach(function (bone) {
  72123. bone.animations.forEach(function (animation) {
  72124. animation.enableBlending = true;
  72125. animation.blendingSpeed = blendingSpeed;
  72126. });
  72127. });
  72128. };
  72129. Skeleton.prototype.dispose = function () {
  72130. this._meshesWithPoseMatrix = [];
  72131. // Animations
  72132. this.getScene().stopAnimation(this);
  72133. // Remove from scene
  72134. this.getScene().removeSkeleton(this);
  72135. };
  72136. Skeleton.prototype.serialize = function () {
  72137. var serializationObject = {};
  72138. serializationObject.name = this.name;
  72139. serializationObject.id = this.id;
  72140. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  72141. serializationObject.bones = [];
  72142. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  72143. for (var index = 0; index < this.bones.length; index++) {
  72144. var bone = this.bones[index];
  72145. var parent_2 = bone.getParent();
  72146. var serializedBone = {
  72147. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  72148. name: bone.name,
  72149. matrix: bone.getBaseMatrix().toArray(),
  72150. rest: bone.getRestPose().toArray()
  72151. };
  72152. serializationObject.bones.push(serializedBone);
  72153. if (bone.length) {
  72154. serializedBone.length = bone.length;
  72155. }
  72156. if (bone.animations && bone.animations.length > 0) {
  72157. serializedBone.animation = bone.animations[0].serialize();
  72158. }
  72159. serializationObject.ranges = [];
  72160. for (var name in this._ranges) {
  72161. var source = this._ranges[name];
  72162. if (!source) {
  72163. continue;
  72164. }
  72165. var range = {};
  72166. range.name = name;
  72167. range.from = source.from;
  72168. range.to = source.to;
  72169. serializationObject.ranges.push(range);
  72170. }
  72171. }
  72172. return serializationObject;
  72173. };
  72174. Skeleton.Parse = function (parsedSkeleton, scene) {
  72175. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  72176. if (parsedSkeleton.dimensionsAtRest) {
  72177. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  72178. }
  72179. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  72180. var index;
  72181. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  72182. var parsedBone = parsedSkeleton.bones[index];
  72183. var parentBone = null;
  72184. if (parsedBone.parentBoneIndex > -1) {
  72185. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  72186. }
  72187. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  72188. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  72189. if (parsedBone.length) {
  72190. bone.length = parsedBone.length;
  72191. }
  72192. if (parsedBone.animation) {
  72193. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  72194. }
  72195. }
  72196. // placed after bones, so createAnimationRange can cascade down
  72197. if (parsedSkeleton.ranges) {
  72198. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  72199. var data = parsedSkeleton.ranges[index];
  72200. skeleton.createAnimationRange(data.name, data.from, data.to);
  72201. }
  72202. }
  72203. return skeleton;
  72204. };
  72205. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  72206. if (forceUpdate === void 0) { forceUpdate = false; }
  72207. var renderId = this._scene.getRenderId();
  72208. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  72209. this.bones[0].computeAbsoluteTransforms();
  72210. this._lastAbsoluteTransformsUpdateId = renderId;
  72211. }
  72212. };
  72213. Skeleton.prototype.getPoseMatrix = function () {
  72214. var poseMatrix = null;
  72215. if (this._meshesWithPoseMatrix.length > 0) {
  72216. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  72217. }
  72218. return poseMatrix;
  72219. };
  72220. Skeleton.prototype.sortBones = function () {
  72221. var bones = new Array();
  72222. var visited = new Array(this.bones.length);
  72223. for (var index = 0; index < this.bones.length; index++) {
  72224. this._sortBones(index, bones, visited);
  72225. }
  72226. this.bones = bones;
  72227. };
  72228. Skeleton.prototype._sortBones = function (index, bones, visited) {
  72229. if (visited[index]) {
  72230. return;
  72231. }
  72232. visited[index] = true;
  72233. var bone = this.bones[index];
  72234. if (bone._index === undefined) {
  72235. bone._index = index;
  72236. }
  72237. var parentBone = bone.getParent();
  72238. if (parentBone) {
  72239. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  72240. }
  72241. bones.push(bone);
  72242. };
  72243. return Skeleton;
  72244. }());
  72245. BABYLON.Skeleton = Skeleton;
  72246. })(BABYLON || (BABYLON = {}));
  72247. //# sourceMappingURL=babylon.skeleton.js.map
  72248. var BABYLON;
  72249. (function (BABYLON) {
  72250. var SphericalPolynomial = /** @class */ (function () {
  72251. function SphericalPolynomial() {
  72252. this.x = BABYLON.Vector3.Zero();
  72253. this.y = BABYLON.Vector3.Zero();
  72254. this.z = BABYLON.Vector3.Zero();
  72255. this.xx = BABYLON.Vector3.Zero();
  72256. this.yy = BABYLON.Vector3.Zero();
  72257. this.zz = BABYLON.Vector3.Zero();
  72258. this.xy = BABYLON.Vector3.Zero();
  72259. this.yz = BABYLON.Vector3.Zero();
  72260. this.zx = BABYLON.Vector3.Zero();
  72261. }
  72262. SphericalPolynomial.prototype.addAmbient = function (color) {
  72263. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  72264. this.xx = this.xx.add(colorVector);
  72265. this.yy = this.yy.add(colorVector);
  72266. this.zz = this.zz.add(colorVector);
  72267. };
  72268. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  72269. var result = new SphericalPolynomial();
  72270. result.x = harmonics.L11.scale(1.02333);
  72271. result.y = harmonics.L1_1.scale(1.02333);
  72272. result.z = harmonics.L10.scale(1.02333);
  72273. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  72274. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  72275. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  72276. result.yz = harmonics.L2_1.scale(0.858086);
  72277. result.zx = harmonics.L21.scale(0.858086);
  72278. result.xy = harmonics.L2_2.scale(0.858086);
  72279. result.scale(1.0 / Math.PI);
  72280. return result;
  72281. };
  72282. SphericalPolynomial.prototype.scale = function (scale) {
  72283. this.x = this.x.scale(scale);
  72284. this.y = this.y.scale(scale);
  72285. this.z = this.z.scale(scale);
  72286. this.xx = this.xx.scale(scale);
  72287. this.yy = this.yy.scale(scale);
  72288. this.zz = this.zz.scale(scale);
  72289. this.yz = this.yz.scale(scale);
  72290. this.zx = this.zx.scale(scale);
  72291. this.xy = this.xy.scale(scale);
  72292. };
  72293. return SphericalPolynomial;
  72294. }());
  72295. BABYLON.SphericalPolynomial = SphericalPolynomial;
  72296. var SphericalHarmonics = /** @class */ (function () {
  72297. function SphericalHarmonics() {
  72298. this.L00 = BABYLON.Vector3.Zero();
  72299. this.L1_1 = BABYLON.Vector3.Zero();
  72300. this.L10 = BABYLON.Vector3.Zero();
  72301. this.L11 = BABYLON.Vector3.Zero();
  72302. this.L2_2 = BABYLON.Vector3.Zero();
  72303. this.L2_1 = BABYLON.Vector3.Zero();
  72304. this.L20 = BABYLON.Vector3.Zero();
  72305. this.L21 = BABYLON.Vector3.Zero();
  72306. this.L22 = BABYLON.Vector3.Zero();
  72307. }
  72308. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  72309. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  72310. var c = colorVector.scale(deltaSolidAngle);
  72311. this.L00 = this.L00.add(c.scale(0.282095));
  72312. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  72313. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  72314. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  72315. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  72316. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  72317. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  72318. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  72319. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  72320. };
  72321. SphericalHarmonics.prototype.scale = function (scale) {
  72322. this.L00 = this.L00.scale(scale);
  72323. this.L1_1 = this.L1_1.scale(scale);
  72324. this.L10 = this.L10.scale(scale);
  72325. this.L11 = this.L11.scale(scale);
  72326. this.L2_2 = this.L2_2.scale(scale);
  72327. this.L2_1 = this.L2_1.scale(scale);
  72328. this.L20 = this.L20.scale(scale);
  72329. this.L21 = this.L21.scale(scale);
  72330. this.L22 = this.L22.scale(scale);
  72331. };
  72332. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  72333. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  72334. //
  72335. // E_lm = A_l * L_lm
  72336. //
  72337. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  72338. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  72339. // the scaling factors are given in equation 9.
  72340. // Constant (Band 0)
  72341. this.L00 = this.L00.scale(3.141593);
  72342. // Linear (Band 1)
  72343. this.L1_1 = this.L1_1.scale(2.094395);
  72344. this.L10 = this.L10.scale(2.094395);
  72345. this.L11 = this.L11.scale(2.094395);
  72346. // Quadratic (Band 2)
  72347. this.L2_2 = this.L2_2.scale(0.785398);
  72348. this.L2_1 = this.L2_1.scale(0.785398);
  72349. this.L20 = this.L20.scale(0.785398);
  72350. this.L21 = this.L21.scale(0.785398);
  72351. this.L22 = this.L22.scale(0.785398);
  72352. };
  72353. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  72354. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  72355. // L = (1/pi) * E * rho
  72356. //
  72357. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  72358. this.scale(1.0 / Math.PI);
  72359. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  72360. // (The pixel shader must apply albedo after texture fetches, etc).
  72361. };
  72362. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  72363. var result = new SphericalHarmonics();
  72364. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  72365. result.L1_1 = polynomial.y.scale(0.977204);
  72366. result.L10 = polynomial.z.scale(0.977204);
  72367. result.L11 = polynomial.x.scale(0.977204);
  72368. result.L2_2 = polynomial.xy.scale(1.16538);
  72369. result.L2_1 = polynomial.yz.scale(1.16538);
  72370. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  72371. result.L21 = polynomial.zx.scale(1.16538);
  72372. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  72373. result.scale(Math.PI);
  72374. return result;
  72375. };
  72376. return SphericalHarmonics;
  72377. }());
  72378. BABYLON.SphericalHarmonics = SphericalHarmonics;
  72379. })(BABYLON || (BABYLON = {}));
  72380. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  72381. var BABYLON;
  72382. (function (BABYLON) {
  72383. var FileFaceOrientation = /** @class */ (function () {
  72384. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  72385. this.name = name;
  72386. this.worldAxisForNormal = worldAxisForNormal;
  72387. this.worldAxisForFileX = worldAxisForFileX;
  72388. this.worldAxisForFileY = worldAxisForFileY;
  72389. }
  72390. return FileFaceOrientation;
  72391. }());
  72392. ;
  72393. /**
  72394. * Helper class dealing with the extraction of spherical polynomial dataArray
  72395. * from a cube map.
  72396. */
  72397. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  72398. function CubeMapToSphericalPolynomialTools() {
  72399. }
  72400. /**
  72401. * Converts a texture to the according Spherical Polynomial data.
  72402. * This extracts the first 3 orders only as they are the only one used in the lighting.
  72403. *
  72404. * @param texture The texture to extract the information from.
  72405. * @return The Spherical Polynomial data.
  72406. */
  72407. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  72408. if (!texture.isCube) {
  72409. // Only supports cube Textures currently.
  72410. return null;
  72411. }
  72412. var size = texture.getSize().width;
  72413. var right = texture.readPixels(0);
  72414. var left = texture.readPixels(1);
  72415. var up;
  72416. var down;
  72417. if (texture.isRenderTarget) {
  72418. up = texture.readPixels(3);
  72419. down = texture.readPixels(2);
  72420. }
  72421. else {
  72422. up = texture.readPixels(2);
  72423. down = texture.readPixels(3);
  72424. }
  72425. var front = texture.readPixels(4);
  72426. var back = texture.readPixels(5);
  72427. var gammaSpace = texture.gammaSpace;
  72428. // Always read as RGBA.
  72429. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  72430. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  72431. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  72432. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  72433. }
  72434. var cubeInfo = {
  72435. size: size,
  72436. right: right,
  72437. left: left,
  72438. up: up,
  72439. down: down,
  72440. front: front,
  72441. back: back,
  72442. format: format,
  72443. type: type,
  72444. gammaSpace: gammaSpace,
  72445. };
  72446. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  72447. };
  72448. /**
  72449. * Converts a cubemap to the according Spherical Polynomial data.
  72450. * This extracts the first 3 orders only as they are the only one used in the lighting.
  72451. *
  72452. * @param cubeInfo The Cube map to extract the information from.
  72453. * @return The Spherical Polynomial data.
  72454. */
  72455. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  72456. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  72457. var totalSolidAngle = 0.0;
  72458. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  72459. var du = 2.0 / cubeInfo.size;
  72460. var dv = du;
  72461. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  72462. var minUV = du * 0.5 - 1.0;
  72463. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  72464. var fileFace = this.FileFaces[faceIndex];
  72465. var dataArray = cubeInfo[fileFace.name];
  72466. var v = minUV;
  72467. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  72468. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  72469. // Because SP is still linear, so summation is fine in that basis.
  72470. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  72471. for (var y = 0; y < cubeInfo.size; y++) {
  72472. var u = minUV;
  72473. for (var x = 0; x < cubeInfo.size; x++) {
  72474. // World direction (not normalised)
  72475. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  72476. worldDirection.normalize();
  72477. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  72478. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  72479. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  72480. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  72481. // Handle Integer types.
  72482. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  72483. r /= 255;
  72484. g /= 255;
  72485. b /= 255;
  72486. }
  72487. // Handle Gamma space textures.
  72488. if (cubeInfo.gammaSpace) {
  72489. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  72490. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  72491. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  72492. }
  72493. var color = new BABYLON.Color3(r, g, b);
  72494. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  72495. totalSolidAngle += deltaSolidAngle;
  72496. u += du;
  72497. }
  72498. v += dv;
  72499. }
  72500. }
  72501. // Solid angle for entire sphere is 4*pi
  72502. var sphereSolidAngle = 4.0 * Math.PI;
  72503. // Adjust the solid angle to allow for how many faces we processed.
  72504. var facesProcessed = 6.0;
  72505. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  72506. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  72507. // This is needed because the numerical integration over the cube uses a
  72508. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  72509. // and also to compensate for accumulative error due to float precision in the summation.
  72510. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  72511. sphericalHarmonics.scale(correctionFactor);
  72512. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  72513. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  72514. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  72515. };
  72516. CubeMapToSphericalPolynomialTools.FileFaces = [
  72517. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  72518. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  72519. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  72520. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  72521. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  72522. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  72523. ];
  72524. return CubeMapToSphericalPolynomialTools;
  72525. }());
  72526. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  72527. })(BABYLON || (BABYLON = {}));
  72528. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  72529. var BABYLON;
  72530. (function (BABYLON) {
  72531. /**
  72532. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  72533. */
  72534. var PanoramaToCubeMapTools = /** @class */ (function () {
  72535. function PanoramaToCubeMapTools() {
  72536. }
  72537. /**
  72538. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  72539. *
  72540. * @param float32Array The source data.
  72541. * @param inputWidth The width of the input panorama.
  72542. * @param inputhHeight The height of the input panorama.
  72543. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  72544. * @return The cubemap data
  72545. */
  72546. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  72547. if (!float32Array) {
  72548. throw "ConvertPanoramaToCubemap: input cannot be null";
  72549. }
  72550. if (float32Array.length != inputWidth * inputHeight * 3) {
  72551. throw "ConvertPanoramaToCubemap: input size is wrong";
  72552. }
  72553. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  72554. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  72555. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  72556. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  72557. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  72558. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  72559. return {
  72560. front: textureFront,
  72561. back: textureBack,
  72562. left: textureLeft,
  72563. right: textureRight,
  72564. up: textureUp,
  72565. down: textureDown,
  72566. size: size,
  72567. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  72568. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  72569. gammaSpace: false,
  72570. };
  72571. };
  72572. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  72573. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  72574. var textureArray = new Float32Array(buffer);
  72575. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  72576. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  72577. var dy = 1 / texSize;
  72578. var fy = 0;
  72579. for (var y = 0; y < texSize; y++) {
  72580. var xv1 = faceData[0];
  72581. var xv2 = faceData[2];
  72582. for (var x = 0; x < texSize; x++) {
  72583. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  72584. v.normalize();
  72585. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  72586. // 3 channels per pixels
  72587. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  72588. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  72589. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  72590. xv1 = xv1.add(rotDX1);
  72591. xv2 = xv2.add(rotDX2);
  72592. }
  72593. fy += dy;
  72594. }
  72595. return textureArray;
  72596. };
  72597. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  72598. var theta = Math.atan2(vDir.z, vDir.x);
  72599. var phi = Math.acos(vDir.y);
  72600. while (theta < -Math.PI)
  72601. theta += 2 * Math.PI;
  72602. while (theta > Math.PI)
  72603. theta -= 2 * Math.PI;
  72604. var dx = theta / Math.PI;
  72605. var dy = phi / Math.PI;
  72606. // recenter.
  72607. dx = dx * 0.5 + 0.5;
  72608. var px = Math.round(dx * inputWidth);
  72609. if (px < 0)
  72610. px = 0;
  72611. else if (px >= inputWidth)
  72612. px = inputWidth - 1;
  72613. var py = Math.round(dy * inputHeight);
  72614. if (py < 0)
  72615. py = 0;
  72616. else if (py >= inputHeight)
  72617. py = inputHeight - 1;
  72618. var inputY = (inputHeight - py - 1);
  72619. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  72620. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  72621. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  72622. return {
  72623. r: r,
  72624. g: g,
  72625. b: b
  72626. };
  72627. };
  72628. PanoramaToCubeMapTools.FACE_FRONT = [
  72629. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72630. new BABYLON.Vector3(1.0, -1.0, -1.0),
  72631. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  72632. new BABYLON.Vector3(1.0, 1.0, -1.0)
  72633. ];
  72634. PanoramaToCubeMapTools.FACE_BACK = [
  72635. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72636. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72637. new BABYLON.Vector3(1.0, 1.0, 1.0),
  72638. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  72639. ];
  72640. PanoramaToCubeMapTools.FACE_RIGHT = [
  72641. new BABYLON.Vector3(1.0, -1.0, -1.0),
  72642. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72643. new BABYLON.Vector3(1.0, 1.0, -1.0),
  72644. new BABYLON.Vector3(1.0, 1.0, 1.0)
  72645. ];
  72646. PanoramaToCubeMapTools.FACE_LEFT = [
  72647. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72648. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72649. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  72650. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  72651. ];
  72652. PanoramaToCubeMapTools.FACE_DOWN = [
  72653. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  72654. new BABYLON.Vector3(1.0, 1.0, -1.0),
  72655. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  72656. new BABYLON.Vector3(1.0, 1.0, 1.0)
  72657. ];
  72658. PanoramaToCubeMapTools.FACE_UP = [
  72659. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72660. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72661. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72662. new BABYLON.Vector3(1.0, -1.0, -1.0)
  72663. ];
  72664. return PanoramaToCubeMapTools;
  72665. }());
  72666. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  72667. })(BABYLON || (BABYLON = {}));
  72668. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  72669. var BABYLON;
  72670. (function (BABYLON) {
  72671. ;
  72672. /**
  72673. * This groups tools to convert HDR texture to native colors array.
  72674. */
  72675. var HDRTools = /** @class */ (function () {
  72676. function HDRTools() {
  72677. }
  72678. HDRTools.Ldexp = function (mantissa, exponent) {
  72679. if (exponent > 1023) {
  72680. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  72681. }
  72682. if (exponent < -1074) {
  72683. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  72684. }
  72685. return mantissa * Math.pow(2, exponent);
  72686. };
  72687. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  72688. if (exponent > 0) {
  72689. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  72690. float32array[index + 0] = red * exponent;
  72691. float32array[index + 1] = green * exponent;
  72692. float32array[index + 2] = blue * exponent;
  72693. }
  72694. else {
  72695. float32array[index + 0] = 0;
  72696. float32array[index + 1] = 0;
  72697. float32array[index + 2] = 0;
  72698. }
  72699. };
  72700. HDRTools.readStringLine = function (uint8array, startIndex) {
  72701. var line = "";
  72702. var character = "";
  72703. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  72704. character = String.fromCharCode(uint8array[i]);
  72705. if (character == "\n") {
  72706. break;
  72707. }
  72708. line += character;
  72709. }
  72710. return line;
  72711. };
  72712. /**
  72713. * Reads header information from an RGBE texture stored in a native array.
  72714. * More information on this format are available here:
  72715. * https://en.wikipedia.org/wiki/RGBE_image_format
  72716. *
  72717. * @param uint8array The binary file stored in native array.
  72718. * @return The header information.
  72719. */
  72720. HDRTools.RGBE_ReadHeader = function (uint8array) {
  72721. var height = 0;
  72722. var width = 0;
  72723. var line = this.readStringLine(uint8array, 0);
  72724. if (line[0] != '#' || line[1] != '?') {
  72725. throw "Bad HDR Format.";
  72726. }
  72727. var endOfHeader = false;
  72728. var findFormat = false;
  72729. var lineIndex = 0;
  72730. do {
  72731. lineIndex += (line.length + 1);
  72732. line = this.readStringLine(uint8array, lineIndex);
  72733. if (line == "FORMAT=32-bit_rle_rgbe") {
  72734. findFormat = true;
  72735. }
  72736. else if (line.length == 0) {
  72737. endOfHeader = true;
  72738. }
  72739. } while (!endOfHeader);
  72740. if (!findFormat) {
  72741. throw "HDR Bad header format, unsupported FORMAT";
  72742. }
  72743. lineIndex += (line.length + 1);
  72744. line = this.readStringLine(uint8array, lineIndex);
  72745. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  72746. var match = sizeRegexp.exec(line);
  72747. // TODO. Support +Y and -X if needed.
  72748. if (!match || match.length < 3) {
  72749. throw "HDR Bad header format, no size";
  72750. }
  72751. width = parseInt(match[2]);
  72752. height = parseInt(match[1]);
  72753. if (width < 8 || width > 0x7fff) {
  72754. throw "HDR Bad header format, unsupported size";
  72755. }
  72756. lineIndex += (line.length + 1);
  72757. return {
  72758. height: height,
  72759. width: width,
  72760. dataPosition: lineIndex
  72761. };
  72762. };
  72763. /**
  72764. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  72765. * This RGBE texture needs to store the information as a panorama.
  72766. *
  72767. * More information on this format are available here:
  72768. * https://en.wikipedia.org/wiki/RGBE_image_format
  72769. *
  72770. * @param buffer The binary file stored in an array buffer.
  72771. * @param size The expected size of the extracted cubemap.
  72772. * @return The Cube Map information.
  72773. */
  72774. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  72775. var uint8array = new Uint8Array(buffer);
  72776. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  72777. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  72778. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  72779. return cubeMapData;
  72780. };
  72781. /**
  72782. * Returns the pixels data extracted from an RGBE texture.
  72783. * This pixels will be stored left to right up to down in the R G B order in one array.
  72784. *
  72785. * More information on this format are available here:
  72786. * https://en.wikipedia.org/wiki/RGBE_image_format
  72787. *
  72788. * @param uint8array The binary file stored in an array buffer.
  72789. * @param hdrInfo The header information of the file.
  72790. * @return The pixels data in RGB right to left up to down order.
  72791. */
  72792. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  72793. // Keep for multi format supports.
  72794. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  72795. };
  72796. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  72797. var num_scanlines = hdrInfo.height;
  72798. var scanline_width = hdrInfo.width;
  72799. var a, b, c, d, count;
  72800. var dataIndex = hdrInfo.dataPosition;
  72801. var index = 0, endIndex = 0, i = 0;
  72802. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  72803. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  72804. // 3 channels of 4 bytes per pixel in float.
  72805. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  72806. var resultArray = new Float32Array(resultBuffer);
  72807. // read in each successive scanline
  72808. while (num_scanlines > 0) {
  72809. a = uint8array[dataIndex++];
  72810. b = uint8array[dataIndex++];
  72811. c = uint8array[dataIndex++];
  72812. d = uint8array[dataIndex++];
  72813. if (a != 2 || b != 2 || (c & 0x80)) {
  72814. // this file is not run length encoded
  72815. throw "HDR Bad header format, not RLE";
  72816. }
  72817. if (((c << 8) | d) != scanline_width) {
  72818. throw "HDR Bad header format, wrong scan line width";
  72819. }
  72820. index = 0;
  72821. // read each of the four channels for the scanline into the buffer
  72822. for (i = 0; i < 4; i++) {
  72823. endIndex = (i + 1) * scanline_width;
  72824. while (index < endIndex) {
  72825. a = uint8array[dataIndex++];
  72826. b = uint8array[dataIndex++];
  72827. if (a > 128) {
  72828. // a run of the same value
  72829. count = a - 128;
  72830. if ((count == 0) || (count > endIndex - index)) {
  72831. throw "HDR Bad Format, bad scanline data (run)";
  72832. }
  72833. while (count-- > 0) {
  72834. scanLineArray[index++] = b;
  72835. }
  72836. }
  72837. else {
  72838. // a non-run
  72839. count = a;
  72840. if ((count == 0) || (count > endIndex - index)) {
  72841. throw "HDR Bad Format, bad scanline data (non-run)";
  72842. }
  72843. scanLineArray[index++] = b;
  72844. if (--count > 0) {
  72845. for (var j = 0; j < count; j++) {
  72846. scanLineArray[index++] = uint8array[dataIndex++];
  72847. }
  72848. }
  72849. }
  72850. }
  72851. }
  72852. // now convert data from buffer into floats
  72853. for (i = 0; i < scanline_width; i++) {
  72854. a = scanLineArray[i];
  72855. b = scanLineArray[i + scanline_width];
  72856. c = scanLineArray[i + 2 * scanline_width];
  72857. d = scanLineArray[i + 3 * scanline_width];
  72858. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  72859. }
  72860. num_scanlines--;
  72861. }
  72862. return resultArray;
  72863. };
  72864. return HDRTools;
  72865. }());
  72866. BABYLON.HDRTools = HDRTools;
  72867. })(BABYLON || (BABYLON = {}));
  72868. //# sourceMappingURL=babylon.hdr.js.map
  72869. var BABYLON;
  72870. (function (BABYLON) {
  72871. /**
  72872. * This represents a texture coming from an HDR input.
  72873. *
  72874. * The only supported format is currently panorama picture stored in RGBE format.
  72875. * Example of such files can be found on HDRLib: http://hdrlib.com/
  72876. */
  72877. var HDRCubeTexture = /** @class */ (function (_super) {
  72878. __extends(HDRCubeTexture, _super);
  72879. /**
  72880. * Instantiates an HDRTexture from the following parameters.
  72881. *
  72882. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  72883. * @param scene The scene the texture will be used in
  72884. * @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.
  72885. * @param noMipmap Forces to not generate the mipmap if true
  72886. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  72887. * @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)
  72888. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  72889. */
  72890. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  72891. if (noMipmap === void 0) { noMipmap = false; }
  72892. if (generateHarmonics === void 0) { generateHarmonics = true; }
  72893. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  72894. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  72895. if (onLoad === void 0) { onLoad = null; }
  72896. if (onError === void 0) { onError = null; }
  72897. var _this = _super.call(this, scene) || this;
  72898. _this._useInGammaSpace = false;
  72899. _this._generateHarmonics = true;
  72900. _this._isBABYLONPreprocessed = false;
  72901. _this._onLoad = null;
  72902. _this._onError = null;
  72903. /**
  72904. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  72905. */
  72906. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  72907. /**
  72908. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  72909. * This is usefull at run time to apply the good shader.
  72910. */
  72911. _this.isPMREM = false;
  72912. _this._isBlocking = true;
  72913. /**
  72914. * Gets or sets the center of the bounding box associated with the cube texture
  72915. * It must define where the camera used to render the texture was set
  72916. */
  72917. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  72918. if (!url) {
  72919. return _this;
  72920. }
  72921. _this.name = url;
  72922. _this.url = url;
  72923. _this.hasAlpha = false;
  72924. _this.isCube = true;
  72925. _this._textureMatrix = BABYLON.Matrix.Identity();
  72926. _this._onLoad = onLoad;
  72927. _this._onError = onError;
  72928. _this.gammaSpace = false;
  72929. var caps = scene.getEngine().getCaps();
  72930. if (size) {
  72931. _this._isBABYLONPreprocessed = false;
  72932. _this._noMipmap = noMipmap;
  72933. _this._size = size;
  72934. _this._useInGammaSpace = useInGammaSpace;
  72935. _this._usePMREMGenerator = usePMREMGenerator &&
  72936. caps.textureLOD &&
  72937. caps.textureFloat &&
  72938. !_this._useInGammaSpace;
  72939. }
  72940. else {
  72941. _this._isBABYLONPreprocessed = true;
  72942. _this._noMipmap = false;
  72943. _this._useInGammaSpace = false;
  72944. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  72945. !_this._useInGammaSpace;
  72946. }
  72947. _this.isPMREM = _this._usePMREMGenerator;
  72948. _this._texture = _this._getFromCache(url, _this._noMipmap);
  72949. if (!_this._texture) {
  72950. if (!scene.useDelayedTextureLoading) {
  72951. _this.loadTexture();
  72952. }
  72953. else {
  72954. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  72955. }
  72956. }
  72957. return _this;
  72958. }
  72959. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  72960. /**
  72961. * Gets wether or not the texture is blocking during loading.
  72962. */
  72963. get: function () {
  72964. return this._isBlocking;
  72965. },
  72966. /**
  72967. * Sets wether or not the texture is blocking during loading.
  72968. */
  72969. set: function (value) {
  72970. this._isBlocking = value;
  72971. },
  72972. enumerable: true,
  72973. configurable: true
  72974. });
  72975. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  72976. get: function () {
  72977. return this._boundingBoxSize;
  72978. },
  72979. /**
  72980. * Gets or sets the size of the bounding box associated with the cube texture
  72981. * When defined, the cubemap will switch to local mode
  72982. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  72983. * @example https://www.babylonjs-playground.com/#RNASML
  72984. */
  72985. set: function (value) {
  72986. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  72987. return;
  72988. }
  72989. this._boundingBoxSize = value;
  72990. var scene = this.getScene();
  72991. if (scene) {
  72992. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  72993. }
  72994. },
  72995. enumerable: true,
  72996. configurable: true
  72997. });
  72998. /**
  72999. * Occurs when the file is a preprocessed .babylon.hdr file.
  73000. */
  73001. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  73002. var _this = this;
  73003. var mipLevels = 0;
  73004. var floatArrayView = null;
  73005. var scene = this.getScene();
  73006. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  73007. var mips = new Array();
  73008. if (!floatArrayView) {
  73009. return mips;
  73010. }
  73011. var startIndex = 30;
  73012. for (var level = 0; level < mipLevels; level++) {
  73013. mips.push([]);
  73014. // Fill each pixel of the mip level.
  73015. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  73016. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  73017. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  73018. mips[level].push(faceData);
  73019. startIndex += faceSize;
  73020. }
  73021. }
  73022. return mips;
  73023. } : null;
  73024. var callback = function (buffer) {
  73025. var scene = _this.getScene();
  73026. if (!scene) {
  73027. return null;
  73028. }
  73029. // Create Native Array Views
  73030. var intArrayView = new Int32Array(buffer);
  73031. floatArrayView = new Float32Array(buffer);
  73032. // Fill header.
  73033. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  73034. _this._size = intArrayView[1]; // CubeMap max mip face size.
  73035. // Update Texture Information.
  73036. if (!_this._texture) {
  73037. return null;
  73038. }
  73039. _this._texture.updateSize(_this._size, _this._size);
  73040. // Fill polynomial information.
  73041. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  73042. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  73043. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  73044. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  73045. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  73046. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  73047. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  73048. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  73049. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  73050. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  73051. _this.sphericalPolynomial = sphericalPolynomial;
  73052. // Fill pixel data.
  73053. mipLevels = intArrayView[29]; // Number of mip levels.
  73054. var startIndex = 30;
  73055. var data = [];
  73056. var faceSize = Math.pow(_this._size, 2) * 3;
  73057. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  73058. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  73059. startIndex += faceSize;
  73060. }
  73061. var results = [];
  73062. var byteArray = null;
  73063. // Push each faces.
  73064. for (var k = 0; k < 6; k++) {
  73065. var dataFace = null;
  73066. // To be deprecated.
  73067. if (version === 1) {
  73068. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  73069. dataFace = data[j];
  73070. }
  73071. // If special cases.
  73072. if (!mipmapGenerator && dataFace) {
  73073. if (!scene.getEngine().getCaps().textureFloat) {
  73074. // 3 channels of 1 bytes per pixel in bytes.
  73075. var byteBuffer = new ArrayBuffer(faceSize);
  73076. byteArray = new Uint8Array(byteBuffer);
  73077. }
  73078. for (var i = 0; i < _this._size * _this._size; i++) {
  73079. // Put in gamma space if requested.
  73080. if (_this._useInGammaSpace) {
  73081. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  73082. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  73083. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  73084. }
  73085. // Convert to int texture for fallback.
  73086. if (byteArray) {
  73087. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  73088. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  73089. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  73090. // May use luminance instead if the result is not accurate.
  73091. var max = Math.max(Math.max(r, g), b);
  73092. if (max > 255) {
  73093. var scale = 255 / max;
  73094. r *= scale;
  73095. g *= scale;
  73096. b *= scale;
  73097. }
  73098. byteArray[(i * 3) + 0] = r;
  73099. byteArray[(i * 3) + 1] = g;
  73100. byteArray[(i * 3) + 2] = b;
  73101. }
  73102. }
  73103. }
  73104. // Fill the array accordingly.
  73105. if (byteArray) {
  73106. results.push(byteArray);
  73107. }
  73108. else {
  73109. results.push(dataFace);
  73110. }
  73111. }
  73112. return results;
  73113. };
  73114. if (scene) {
  73115. 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);
  73116. }
  73117. };
  73118. /**
  73119. * Occurs when the file is raw .hdr file.
  73120. */
  73121. HDRCubeTexture.prototype.loadHDRTexture = function () {
  73122. var _this = this;
  73123. var callback = function (buffer) {
  73124. var scene = _this.getScene();
  73125. if (!scene) {
  73126. return null;
  73127. }
  73128. // Extract the raw linear data.
  73129. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  73130. // Generate harmonics if needed.
  73131. if (_this._generateHarmonics) {
  73132. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  73133. _this.sphericalPolynomial = sphericalPolynomial;
  73134. }
  73135. var results = [];
  73136. var byteArray = null;
  73137. // Push each faces.
  73138. for (var j = 0; j < 6; j++) {
  73139. // Create uintarray fallback.
  73140. if (!scene.getEngine().getCaps().textureFloat) {
  73141. // 3 channels of 1 bytes per pixel in bytes.
  73142. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  73143. byteArray = new Uint8Array(byteBuffer);
  73144. }
  73145. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  73146. // If special cases.
  73147. if (_this._useInGammaSpace || byteArray) {
  73148. for (var i = 0; i < _this._size * _this._size; i++) {
  73149. // Put in gamma space if requested.
  73150. if (_this._useInGammaSpace) {
  73151. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  73152. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  73153. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  73154. }
  73155. // Convert to int texture for fallback.
  73156. if (byteArray) {
  73157. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  73158. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  73159. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  73160. // May use luminance instead if the result is not accurate.
  73161. var max = Math.max(Math.max(r, g), b);
  73162. if (max > 255) {
  73163. var scale = 255 / max;
  73164. r *= scale;
  73165. g *= scale;
  73166. b *= scale;
  73167. }
  73168. byteArray[(i * 3) + 0] = r;
  73169. byteArray[(i * 3) + 1] = g;
  73170. byteArray[(i * 3) + 2] = b;
  73171. }
  73172. }
  73173. }
  73174. if (byteArray) {
  73175. results.push(byteArray);
  73176. }
  73177. else {
  73178. results.push(dataFace);
  73179. }
  73180. }
  73181. return results;
  73182. };
  73183. var mipmapGenerator = null;
  73184. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  73185. // if (!this._noMipmap &&
  73186. // this._usePMREMGenerator) {
  73187. // mipmapGenerator = (data: ArrayBufferView[]) => {
  73188. // // Custom setup of the generator matching with the PBR shader values.
  73189. // var generator = new BABYLON.PMREMGenerator(data,
  73190. // this._size,
  73191. // this._size,
  73192. // 0,
  73193. // 3,
  73194. // this.getScene().getEngine().getCaps().textureFloat,
  73195. // 2048,
  73196. // 0.25,
  73197. // false,
  73198. // true);
  73199. // return generator.filterCubeMap();
  73200. // };
  73201. // }
  73202. var scene = this.getScene();
  73203. if (scene) {
  73204. 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);
  73205. }
  73206. };
  73207. /**
  73208. * Starts the loading process of the texture.
  73209. */
  73210. HDRCubeTexture.prototype.loadTexture = function () {
  73211. if (this._isBABYLONPreprocessed) {
  73212. this.loadBabylonTexture();
  73213. }
  73214. else {
  73215. this.loadHDRTexture();
  73216. }
  73217. };
  73218. HDRCubeTexture.prototype.clone = function () {
  73219. var scene = this.getScene();
  73220. if (!scene) {
  73221. return this;
  73222. }
  73223. var size = (this._isBABYLONPreprocessed ? null : this._size);
  73224. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  73225. // Base texture
  73226. newTexture.level = this.level;
  73227. newTexture.wrapU = this.wrapU;
  73228. newTexture.wrapV = this.wrapV;
  73229. newTexture.coordinatesIndex = this.coordinatesIndex;
  73230. newTexture.coordinatesMode = this.coordinatesMode;
  73231. return newTexture;
  73232. };
  73233. // Methods
  73234. HDRCubeTexture.prototype.delayLoad = function () {
  73235. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  73236. return;
  73237. }
  73238. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  73239. this._texture = this._getFromCache(this.url, this._noMipmap);
  73240. if (!this._texture) {
  73241. this.loadTexture();
  73242. }
  73243. };
  73244. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  73245. return this._textureMatrix;
  73246. };
  73247. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  73248. this._textureMatrix = value;
  73249. };
  73250. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  73251. var texture = null;
  73252. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  73253. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  73254. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  73255. texture.name = parsedTexture.name;
  73256. texture.hasAlpha = parsedTexture.hasAlpha;
  73257. texture.level = parsedTexture.level;
  73258. texture.coordinatesMode = parsedTexture.coordinatesMode;
  73259. texture.isBlocking = parsedTexture.isBlocking;
  73260. }
  73261. if (texture) {
  73262. if (parsedTexture.boundingBoxPosition) {
  73263. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  73264. }
  73265. if (parsedTexture.boundingBoxSize) {
  73266. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  73267. }
  73268. }
  73269. return texture;
  73270. };
  73271. HDRCubeTexture.prototype.serialize = function () {
  73272. if (!this.name) {
  73273. return null;
  73274. }
  73275. var serializationObject = {};
  73276. serializationObject.name = this.name;
  73277. serializationObject.hasAlpha = this.hasAlpha;
  73278. serializationObject.isCube = true;
  73279. serializationObject.level = this.level;
  73280. serializationObject.size = this._size;
  73281. serializationObject.coordinatesMode = this.coordinatesMode;
  73282. serializationObject.useInGammaSpace = this._useInGammaSpace;
  73283. serializationObject.generateHarmonics = this._generateHarmonics;
  73284. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  73285. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  73286. serializationObject.customType = "BABYLON.HDRCubeTexture";
  73287. serializationObject.noMipmap = this._noMipmap;
  73288. serializationObject.isBlocking = this._isBlocking;
  73289. return serializationObject;
  73290. };
  73291. /**
  73292. * Saves as a file the data contained in the texture in a binary format.
  73293. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  73294. * as the spherical used in the lighting.
  73295. * @param url The HDR file url.
  73296. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  73297. * @param onError Method called if any error happens during download.
  73298. * @return The packed binary data.
  73299. */
  73300. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  73301. if (onError === void 0) { onError = null; }
  73302. var callback = function (buffer) {
  73303. var data = new Blob([buffer], { type: 'application/octet-stream' });
  73304. // Returns a URL you can use as a href.
  73305. var objUrl = window.URL.createObjectURL(data);
  73306. // Simulates a link to it and click to dowload.
  73307. var a = document.createElement("a");
  73308. document.body.appendChild(a);
  73309. a.style.display = "none";
  73310. a.href = objUrl;
  73311. a.download = "envmap.babylon.hdr";
  73312. a.click();
  73313. };
  73314. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  73315. };
  73316. /**
  73317. * Serializes the data contained in the texture in a binary format.
  73318. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  73319. * as the spherical used in the lighting.
  73320. * @param url The HDR file url.
  73321. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  73322. * @param onError Method called if any error happens during download.
  73323. * @return The packed binary data.
  73324. */
  73325. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  73326. if (onError === void 0) { onError = null; }
  73327. // Needs the url tho create the texture.
  73328. if (!url) {
  73329. return;
  73330. }
  73331. // Check Power of two size.
  73332. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  73333. return;
  73334. }
  73335. // Coming Back in 3.x.
  73336. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  73337. };
  73338. HDRCubeTexture._facesMapping = [
  73339. "right",
  73340. "left",
  73341. "up",
  73342. "down",
  73343. "front",
  73344. "back"
  73345. ];
  73346. return HDRCubeTexture;
  73347. }(BABYLON.BaseTexture));
  73348. BABYLON.HDRCubeTexture = HDRCubeTexture;
  73349. })(BABYLON || (BABYLON = {}));
  73350. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  73351. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  73352. // Huge respect for a such great lib.
  73353. // Earcut license:
  73354. // Copyright (c) 2016, Mapbox
  73355. //
  73356. // Permission to use, copy, modify, and/or distribute this software for any purpose
  73357. // with or without fee is hereby granted, provided that the above copyright notice
  73358. // and this permission notice appear in all copies.
  73359. //
  73360. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  73361. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  73362. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  73363. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  73364. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  73365. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  73366. // THIS SOFTWARE.
  73367. var Earcut;
  73368. (function (Earcut) {
  73369. /**
  73370. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  73371. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  73372. * @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).
  73373. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  73374. */
  73375. function earcut(data, holeIndices, dim) {
  73376. dim = dim || 2;
  73377. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  73378. if (!outerNode)
  73379. return triangles;
  73380. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  73381. if (hasHoles)
  73382. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  73383. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  73384. if (data.length > 80 * dim) {
  73385. minX = maxX = data[0];
  73386. minY = maxY = data[1];
  73387. for (var i = dim; i < outerLen; i += dim) {
  73388. x = data[i];
  73389. y = data[i + 1];
  73390. if (x < minX)
  73391. minX = x;
  73392. if (y < minY)
  73393. minY = y;
  73394. if (x > maxX)
  73395. maxX = x;
  73396. if (y > maxY)
  73397. maxY = y;
  73398. }
  73399. // minX, minY and size are later used to transform coords into integers for z-order calculation
  73400. size = Math.max(maxX - minX, maxY - minY);
  73401. }
  73402. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  73403. return triangles;
  73404. }
  73405. Earcut.earcut = earcut;
  73406. var Node = /** @class */ (function () {
  73407. function Node(i, x, y) {
  73408. this.i = i;
  73409. this.x = x;
  73410. this.y = y;
  73411. this.prev = null;
  73412. this.next = null;
  73413. this.z = null;
  73414. this.prevZ = null;
  73415. this.nextZ = null;
  73416. this.steiner = false;
  73417. }
  73418. return Node;
  73419. }());
  73420. // create a circular doubly linked list from polygon points in the specified winding order
  73421. function linkedList(data, start, end, dim, clockwise) {
  73422. var i, last = null;
  73423. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  73424. for (i = start; i < end; i += dim)
  73425. last = insertNode(i, data[i], data[i + 1], last);
  73426. }
  73427. else {
  73428. for (i = end - dim; i >= start; i -= dim)
  73429. last = insertNode(i, data[i], data[i + 1], last);
  73430. }
  73431. if (last && equals(last, last.next)) {
  73432. removeNode(last);
  73433. last = last.next;
  73434. }
  73435. return last;
  73436. }
  73437. // eliminate colinear or duplicate points
  73438. function filterPoints(start, end) {
  73439. if (!start)
  73440. return start;
  73441. if (!end)
  73442. end = start;
  73443. var p = start, again;
  73444. do {
  73445. again = false;
  73446. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  73447. removeNode(p);
  73448. p = end = p.prev;
  73449. if (p === p.next)
  73450. return undefined;
  73451. again = true;
  73452. }
  73453. else {
  73454. p = p.next;
  73455. }
  73456. } while (again || p !== end);
  73457. return end;
  73458. }
  73459. // main ear slicing loop which triangulates a polygon (given as a linked list)
  73460. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  73461. if (!ear)
  73462. return;
  73463. // interlink polygon nodes in z-order
  73464. if (!pass && size)
  73465. indexCurve(ear, minX, minY, size);
  73466. var stop = ear, prev, next;
  73467. // iterate through ears, slicing them one by one
  73468. while (ear.prev !== ear.next) {
  73469. prev = ear.prev;
  73470. next = ear.next;
  73471. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  73472. // cut off the triangle
  73473. triangles.push(prev.i / dim);
  73474. triangles.push(ear.i / dim);
  73475. triangles.push(next.i / dim);
  73476. removeNode(ear);
  73477. // skipping the next vertice leads to less sliver triangles
  73478. ear = next.next;
  73479. stop = next.next;
  73480. continue;
  73481. }
  73482. ear = next;
  73483. // if we looped through the whole remaining polygon and can't find any more ears
  73484. if (ear === stop) {
  73485. // try filtering points and slicing again
  73486. if (!pass) {
  73487. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  73488. // if this didn't work, try curing all small self-intersections locally
  73489. }
  73490. else if (pass === 1) {
  73491. ear = cureLocalIntersections(ear, triangles, dim);
  73492. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  73493. // as a last resort, try splitting the remaining polygon into two
  73494. }
  73495. else if (pass === 2) {
  73496. splitEarcut(ear, triangles, dim, minX, minY, size);
  73497. }
  73498. break;
  73499. }
  73500. }
  73501. }
  73502. // check whether a polygon node forms a valid ear with adjacent nodes
  73503. function isEar(ear) {
  73504. var a = ear.prev, b = ear, c = ear.next;
  73505. if (area(a, b, c) >= 0)
  73506. return false; // reflex, can't be an ear
  73507. // now make sure we don't have other points inside the potential ear
  73508. var p = ear.next.next;
  73509. while (p !== ear.prev) {
  73510. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  73511. area(p.prev, p, p.next) >= 0)
  73512. return false;
  73513. p = p.next;
  73514. }
  73515. return true;
  73516. }
  73517. function isEarHashed(ear, minX, minY, size) {
  73518. var a = ear.prev, b = ear, c = ear.next;
  73519. if (area(a, b, c) >= 0)
  73520. return false; // reflex, can't be an ear
  73521. // triangle bbox; min & max are calculated like this for speed
  73522. 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);
  73523. // z-order range for the current triangle bbox;
  73524. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  73525. // first look for points inside the triangle in increasing z-order
  73526. var p = ear.nextZ;
  73527. while (p && p.z <= maxZ) {
  73528. if (p !== ear.prev &&
  73529. p !== ear.next &&
  73530. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  73531. area(p.prev, p, p.next) >= 0)
  73532. return false;
  73533. p = p.nextZ;
  73534. }
  73535. // then look for points in decreasing z-order
  73536. p = ear.prevZ;
  73537. while (p && p.z >= minZ) {
  73538. if (p !== ear.prev &&
  73539. p !== ear.next &&
  73540. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  73541. area(p.prev, p, p.next) >= 0)
  73542. return false;
  73543. p = p.prevZ;
  73544. }
  73545. return true;
  73546. }
  73547. // go through all polygon nodes and cure small local self-intersections
  73548. function cureLocalIntersections(start, triangles, dim) {
  73549. var p = start;
  73550. do {
  73551. var a = p.prev, b = p.next.next;
  73552. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  73553. triangles.push(a.i / dim);
  73554. triangles.push(p.i / dim);
  73555. triangles.push(b.i / dim);
  73556. // remove two nodes involved
  73557. removeNode(p);
  73558. removeNode(p.next);
  73559. p = start = b;
  73560. }
  73561. p = p.next;
  73562. } while (p !== start);
  73563. return p;
  73564. }
  73565. // try splitting polygon into two and triangulate them independently
  73566. function splitEarcut(start, triangles, dim, minX, minY, size) {
  73567. // look for a valid diagonal that divides the polygon into two
  73568. var a = start;
  73569. do {
  73570. var b = a.next.next;
  73571. while (b !== a.prev) {
  73572. if (a.i !== b.i && isValidDiagonal(a, b)) {
  73573. // split the polygon in two by the diagonal
  73574. var c = splitPolygon(a, b);
  73575. // filter colinear points around the cuts
  73576. a = filterPoints(a, a.next);
  73577. c = filterPoints(c, c.next);
  73578. // run earcut on each half
  73579. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  73580. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  73581. return;
  73582. }
  73583. b = b.next;
  73584. }
  73585. a = a.next;
  73586. } while (a !== start);
  73587. }
  73588. // link every hole into the outer loop, producing a single-ring polygon without holes
  73589. function eliminateHoles(data, holeIndices, outerNode, dim) {
  73590. var queue = [], i, len, start, end, list;
  73591. for (i = 0, len = holeIndices.length; i < len; i++) {
  73592. start = holeIndices[i] * dim;
  73593. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  73594. list = linkedList(data, start, end, dim, false);
  73595. if (list === list.next)
  73596. list.steiner = true;
  73597. queue.push(getLeftmost(list));
  73598. }
  73599. queue.sort(compareX);
  73600. // process holes from left to right
  73601. for (i = 0; i < queue.length; i++) {
  73602. eliminateHole(queue[i], outerNode);
  73603. outerNode = filterPoints(outerNode, outerNode.next);
  73604. }
  73605. return outerNode;
  73606. }
  73607. function compareX(a, b) {
  73608. return a.x - b.x;
  73609. }
  73610. // find a bridge between vertices that connects hole with an outer ring and and link it
  73611. function eliminateHole(hole, outerNode) {
  73612. outerNode = findHoleBridge(hole, outerNode);
  73613. if (outerNode) {
  73614. var b = splitPolygon(outerNode, hole);
  73615. filterPoints(b, b.next);
  73616. }
  73617. }
  73618. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  73619. function findHoleBridge(hole, outerNode) {
  73620. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  73621. // find a segment intersected by a ray from the hole's leftmost point to the left;
  73622. // segment's endpoint with lesser x will be potential connection point
  73623. do {
  73624. if (hy <= p.y && hy >= p.next.y) {
  73625. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  73626. if (x <= hx && x > qx) {
  73627. qx = x;
  73628. if (x === hx) {
  73629. if (hy === p.y)
  73630. return p;
  73631. if (hy === p.next.y)
  73632. return p.next;
  73633. }
  73634. m = p.x < p.next.x ? p : p.next;
  73635. }
  73636. }
  73637. p = p.next;
  73638. } while (p !== outerNode);
  73639. if (!m)
  73640. return null;
  73641. if (hx === qx)
  73642. return m.prev; // hole touches outer segment; pick lower endpoint
  73643. // look for points inside the triangle of hole point, segment intersection and endpoint;
  73644. // if there are no points found, we have a valid connection;
  73645. // otherwise choose the point of the minimum angle with the ray as connection point
  73646. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  73647. p = m.next;
  73648. while (p !== stop) {
  73649. if (hx >= p.x &&
  73650. p.x >= mx &&
  73651. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  73652. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  73653. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  73654. m = p;
  73655. tanMin = tan;
  73656. }
  73657. }
  73658. p = p.next;
  73659. }
  73660. return m;
  73661. }
  73662. // interlink polygon nodes in z-order
  73663. function indexCurve(start, minX, minY, size) {
  73664. var p = start;
  73665. do {
  73666. if (p.z === null)
  73667. p.z = zOrder(p.x, p.y, minX, minY, size);
  73668. p.prevZ = p.prev;
  73669. p.nextZ = p.next;
  73670. p = p.next;
  73671. } while (p !== start);
  73672. p.prevZ.nextZ = null;
  73673. p.prevZ = null;
  73674. sortLinked(p);
  73675. }
  73676. // Simon Tatham's linked list merge sort algorithm
  73677. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  73678. function sortLinked(list) {
  73679. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  73680. do {
  73681. p = list;
  73682. list = null;
  73683. tail = null;
  73684. numMerges = 0;
  73685. while (p) {
  73686. numMerges++;
  73687. q = p;
  73688. pSize = 0;
  73689. for (i = 0; i < inSize; i++) {
  73690. pSize++;
  73691. q = q.nextZ;
  73692. if (!q)
  73693. break;
  73694. }
  73695. qSize = inSize;
  73696. while (pSize > 0 || (qSize > 0 && q)) {
  73697. if (pSize === 0) {
  73698. e = q;
  73699. q = q.nextZ;
  73700. qSize--;
  73701. }
  73702. else if (qSize === 0 || !q) {
  73703. e = p;
  73704. p = p.nextZ;
  73705. pSize--;
  73706. }
  73707. else if (p.z <= q.z) {
  73708. e = p;
  73709. p = p.nextZ;
  73710. pSize--;
  73711. }
  73712. else {
  73713. e = q;
  73714. q = q.nextZ;
  73715. qSize--;
  73716. }
  73717. if (tail)
  73718. tail.nextZ = e;
  73719. else
  73720. list = e;
  73721. e.prevZ = tail;
  73722. tail = e;
  73723. }
  73724. p = q;
  73725. }
  73726. tail.nextZ = null;
  73727. inSize *= 2;
  73728. } while (numMerges > 1);
  73729. return list;
  73730. }
  73731. // z-order of a point given coords and size of the data bounding box
  73732. function zOrder(x, y, minX, minY, size) {
  73733. // coords are transformed into non-negative 15-bit integer range
  73734. x = 32767 * (x - minX) / size;
  73735. y = 32767 * (y - minY) / size;
  73736. x = (x | (x << 8)) & 0x00FF00FF;
  73737. x = (x | (x << 4)) & 0x0F0F0F0F;
  73738. x = (x | (x << 2)) & 0x33333333;
  73739. x = (x | (x << 1)) & 0x55555555;
  73740. y = (y | (y << 8)) & 0x00FF00FF;
  73741. y = (y | (y << 4)) & 0x0F0F0F0F;
  73742. y = (y | (y << 2)) & 0x33333333;
  73743. y = (y | (y << 1)) & 0x55555555;
  73744. return x | (y << 1);
  73745. }
  73746. // find the leftmost node of a polygon ring
  73747. function getLeftmost(start) {
  73748. var p = start, leftmost = start;
  73749. do {
  73750. if (p.x < leftmost.x)
  73751. leftmost = p;
  73752. p = p.next;
  73753. } while (p !== start);
  73754. return leftmost;
  73755. }
  73756. // check if a point lies within a convex triangle
  73757. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  73758. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  73759. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  73760. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  73761. }
  73762. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  73763. function isValidDiagonal(a, b) {
  73764. return a.next.i !== b.i &&
  73765. a.prev.i !== b.i &&
  73766. !intersectsPolygon(a, b) &&
  73767. locallyInside(a, b) &&
  73768. locallyInside(b, a) &&
  73769. middleInside(a, b);
  73770. }
  73771. // signed area of a triangle
  73772. function area(p, q, r) {
  73773. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  73774. }
  73775. // check if two points are equal
  73776. function equals(p1, p2) {
  73777. return p1.x === p2.x && p1.y === p2.y;
  73778. }
  73779. // check if two segments intersect
  73780. function intersects(p1, q1, p2, q2) {
  73781. if ((equals(p1, q1) && equals(p2, q2)) ||
  73782. (equals(p1, q2) && equals(p2, q1)))
  73783. return true;
  73784. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  73785. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  73786. }
  73787. // check if a polygon diagonal intersects any polygon segments
  73788. function intersectsPolygon(a, b) {
  73789. var p = a;
  73790. do {
  73791. if (p.i !== a.i &&
  73792. p.next.i !== a.i &&
  73793. p.i !== b.i &&
  73794. p.next.i !== b.i &&
  73795. intersects(p, p.next, a, b))
  73796. return true;
  73797. p = p.next;
  73798. } while (p !== a);
  73799. return false;
  73800. }
  73801. // check if a polygon diagonal is locally inside the polygon
  73802. function locallyInside(a, b) {
  73803. return area(a.prev, a, a.next) < 0
  73804. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  73805. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  73806. }
  73807. // check if the middle point of a polygon diagonal is inside the polygon
  73808. function middleInside(a, b) {
  73809. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  73810. do {
  73811. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  73812. inside = !inside;
  73813. p = p.next;
  73814. } while (p !== a);
  73815. return inside;
  73816. }
  73817. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  73818. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  73819. function splitPolygon(a, b) {
  73820. 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;
  73821. a.next = b;
  73822. b.prev = a;
  73823. a2.next = an;
  73824. an.prev = a2;
  73825. b2.next = a2;
  73826. a2.prev = b2;
  73827. bp.next = b2;
  73828. b2.prev = bp;
  73829. return b2;
  73830. }
  73831. // create a node and optionally link it with previous one (in a circular doubly linked list)
  73832. function insertNode(i, x, y, last) {
  73833. var p = new Node(i, x, y);
  73834. if (!last) {
  73835. p.prev = p;
  73836. p.next = p;
  73837. }
  73838. else {
  73839. p.next = last.next;
  73840. p.prev = last;
  73841. last.next.prev = p;
  73842. last.next = p;
  73843. }
  73844. return p;
  73845. }
  73846. function removeNode(p) {
  73847. p.next.prev = p.prev;
  73848. p.prev.next = p.next;
  73849. if (p.prevZ)
  73850. p.prevZ.nextZ = p.nextZ;
  73851. if (p.nextZ)
  73852. p.nextZ.prevZ = p.prevZ;
  73853. }
  73854. /**
  73855. * return a percentage difference between the polygon area and its triangulation area;
  73856. * used to verify correctness of triangulation
  73857. */
  73858. function deviation(data, holeIndices, dim, triangles) {
  73859. var hasHoles = holeIndices && holeIndices.length;
  73860. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  73861. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  73862. if (hasHoles) {
  73863. for (var i = 0, len = holeIndices.length; i < len; i++) {
  73864. var start = holeIndices[i] * dim;
  73865. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  73866. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  73867. }
  73868. }
  73869. var trianglesArea = 0;
  73870. for (i = 0; i < triangles.length; i += 3) {
  73871. var a = triangles[i] * dim;
  73872. var b = triangles[i + 1] * dim;
  73873. var c = triangles[i + 2] * dim;
  73874. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  73875. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  73876. }
  73877. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  73878. }
  73879. Earcut.deviation = deviation;
  73880. ;
  73881. function signedArea(data, start, end, dim) {
  73882. var sum = 0;
  73883. for (var i = start, j = end - dim; i < end; i += dim) {
  73884. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  73885. j = i;
  73886. }
  73887. return sum;
  73888. }
  73889. /**
  73890. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  73891. */
  73892. function flatten(data) {
  73893. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  73894. for (var i = 0; i < data.length; i++) {
  73895. for (var j = 0; j < data[i].length; j++) {
  73896. for (var d = 0; d < dim; d++)
  73897. result.vertices.push(data[i][j][d]);
  73898. }
  73899. if (i > 0) {
  73900. holeIndex += data[i - 1].length;
  73901. result.holes.push(holeIndex);
  73902. }
  73903. }
  73904. return result;
  73905. }
  73906. Earcut.flatten = flatten;
  73907. ;
  73908. })(Earcut || (Earcut = {}));
  73909. //# sourceMappingURL=babylon.earcut.js.map
  73910. var BABYLON;
  73911. (function (BABYLON) {
  73912. var IndexedVector2 = /** @class */ (function (_super) {
  73913. __extends(IndexedVector2, _super);
  73914. function IndexedVector2(original, index) {
  73915. var _this = _super.call(this, original.x, original.y) || this;
  73916. _this.index = index;
  73917. return _this;
  73918. }
  73919. return IndexedVector2;
  73920. }(BABYLON.Vector2));
  73921. var PolygonPoints = /** @class */ (function () {
  73922. function PolygonPoints() {
  73923. this.elements = new Array();
  73924. }
  73925. PolygonPoints.prototype.add = function (originalPoints) {
  73926. var _this = this;
  73927. var result = new Array();
  73928. originalPoints.forEach(function (point) {
  73929. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  73930. var newPoint = new IndexedVector2(point, _this.elements.length);
  73931. result.push(newPoint);
  73932. _this.elements.push(newPoint);
  73933. }
  73934. });
  73935. return result;
  73936. };
  73937. PolygonPoints.prototype.computeBounds = function () {
  73938. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  73939. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  73940. this.elements.forEach(function (point) {
  73941. // x
  73942. if (point.x < lmin.x) {
  73943. lmin.x = point.x;
  73944. }
  73945. else if (point.x > lmax.x) {
  73946. lmax.x = point.x;
  73947. }
  73948. // y
  73949. if (point.y < lmin.y) {
  73950. lmin.y = point.y;
  73951. }
  73952. else if (point.y > lmax.y) {
  73953. lmax.y = point.y;
  73954. }
  73955. });
  73956. return {
  73957. min: lmin,
  73958. max: lmax,
  73959. width: lmax.x - lmin.x,
  73960. height: lmax.y - lmin.y
  73961. };
  73962. };
  73963. return PolygonPoints;
  73964. }());
  73965. var Polygon = /** @class */ (function () {
  73966. function Polygon() {
  73967. }
  73968. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  73969. return [
  73970. new BABYLON.Vector2(xmin, ymin),
  73971. new BABYLON.Vector2(xmax, ymin),
  73972. new BABYLON.Vector2(xmax, ymax),
  73973. new BABYLON.Vector2(xmin, ymax)
  73974. ];
  73975. };
  73976. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  73977. if (cx === void 0) { cx = 0; }
  73978. if (cy === void 0) { cy = 0; }
  73979. if (numberOfSides === void 0) { numberOfSides = 32; }
  73980. var result = new Array();
  73981. var angle = 0;
  73982. var increment = (Math.PI * 2) / numberOfSides;
  73983. for (var i = 0; i < numberOfSides; i++) {
  73984. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  73985. angle -= increment;
  73986. }
  73987. return result;
  73988. };
  73989. Polygon.Parse = function (input) {
  73990. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  73991. var i, result = [];
  73992. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  73993. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  73994. }
  73995. return result;
  73996. };
  73997. Polygon.StartingAt = function (x, y) {
  73998. return BABYLON.Path2.StartingAt(x, y);
  73999. };
  74000. return Polygon;
  74001. }());
  74002. BABYLON.Polygon = Polygon;
  74003. var PolygonMeshBuilder = /** @class */ (function () {
  74004. function PolygonMeshBuilder(name, contours, scene) {
  74005. this._points = new PolygonPoints();
  74006. this._outlinepoints = new PolygonPoints();
  74007. this._holes = new Array();
  74008. this._epoints = new Array();
  74009. this._eholes = new Array();
  74010. this._name = name;
  74011. this._scene = scene;
  74012. var points;
  74013. if (contours instanceof BABYLON.Path2) {
  74014. points = contours.getPoints();
  74015. }
  74016. else {
  74017. points = contours;
  74018. }
  74019. this._addToepoint(points);
  74020. this._points.add(points);
  74021. this._outlinepoints.add(points);
  74022. }
  74023. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  74024. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  74025. var p = points_1[_i];
  74026. this._epoints.push(p.x, p.y);
  74027. }
  74028. };
  74029. PolygonMeshBuilder.prototype.addHole = function (hole) {
  74030. this._points.add(hole);
  74031. var holepoints = new PolygonPoints();
  74032. holepoints.add(hole);
  74033. this._holes.push(holepoints);
  74034. this._eholes.push(this._epoints.length / 2);
  74035. this._addToepoint(hole);
  74036. return this;
  74037. };
  74038. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  74039. var _this = this;
  74040. if (updatable === void 0) { updatable = false; }
  74041. if (depth === void 0) { depth = 0; }
  74042. var result = new BABYLON.Mesh(this._name, this._scene);
  74043. var normals = new Array();
  74044. var positions = new Array();
  74045. var uvs = new Array();
  74046. var bounds = this._points.computeBounds();
  74047. this._points.elements.forEach(function (p) {
  74048. normals.push(0, 1.0, 0);
  74049. positions.push(p.x, 0, p.y);
  74050. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  74051. });
  74052. var indices = new Array();
  74053. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  74054. for (var i = 0; i < res.length; i++) {
  74055. indices.push(res[i]);
  74056. }
  74057. if (depth > 0) {
  74058. var positionscount = (positions.length / 3); //get the current pointcount
  74059. this._points.elements.forEach(function (p) {
  74060. normals.push(0, -1.0, 0);
  74061. positions.push(p.x, -depth, p.y);
  74062. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  74063. });
  74064. var totalCount = indices.length;
  74065. for (var i = 0; i < totalCount; i += 3) {
  74066. var i0 = indices[i + 0];
  74067. var i1 = indices[i + 1];
  74068. var i2 = indices[i + 2];
  74069. indices.push(i2 + positionscount);
  74070. indices.push(i1 + positionscount);
  74071. indices.push(i0 + positionscount);
  74072. }
  74073. //Add the sides
  74074. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  74075. this._holes.forEach(function (hole) {
  74076. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  74077. });
  74078. }
  74079. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  74080. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  74081. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  74082. result.setIndices(indices);
  74083. return result;
  74084. };
  74085. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  74086. var StartIndex = positions.length / 3;
  74087. var ulength = 0;
  74088. for (var i = 0; i < points.elements.length; i++) {
  74089. var p = points.elements[i];
  74090. var p1;
  74091. if ((i + 1) > points.elements.length - 1) {
  74092. p1 = points.elements[0];
  74093. }
  74094. else {
  74095. p1 = points.elements[i + 1];
  74096. }
  74097. positions.push(p.x, 0, p.y);
  74098. positions.push(p.x, -depth, p.y);
  74099. positions.push(p1.x, 0, p1.y);
  74100. positions.push(p1.x, -depth, p1.y);
  74101. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  74102. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  74103. var v3 = v2.subtract(v1);
  74104. var v4 = new BABYLON.Vector3(0, 1, 0);
  74105. var vn = BABYLON.Vector3.Cross(v3, v4);
  74106. vn = vn.normalize();
  74107. uvs.push(ulength / bounds.width, 0);
  74108. uvs.push(ulength / bounds.width, 1);
  74109. ulength += v3.length();
  74110. uvs.push((ulength / bounds.width), 0);
  74111. uvs.push((ulength / bounds.width), 1);
  74112. if (!flip) {
  74113. normals.push(-vn.x, -vn.y, -vn.z);
  74114. normals.push(-vn.x, -vn.y, -vn.z);
  74115. normals.push(-vn.x, -vn.y, -vn.z);
  74116. normals.push(-vn.x, -vn.y, -vn.z);
  74117. indices.push(StartIndex);
  74118. indices.push(StartIndex + 1);
  74119. indices.push(StartIndex + 2);
  74120. indices.push(StartIndex + 1);
  74121. indices.push(StartIndex + 3);
  74122. indices.push(StartIndex + 2);
  74123. }
  74124. else {
  74125. normals.push(vn.x, vn.y, vn.z);
  74126. normals.push(vn.x, vn.y, vn.z);
  74127. normals.push(vn.x, vn.y, vn.z);
  74128. normals.push(vn.x, vn.y, vn.z);
  74129. indices.push(StartIndex);
  74130. indices.push(StartIndex + 2);
  74131. indices.push(StartIndex + 1);
  74132. indices.push(StartIndex + 1);
  74133. indices.push(StartIndex + 2);
  74134. indices.push(StartIndex + 3);
  74135. }
  74136. StartIndex += 4;
  74137. }
  74138. ;
  74139. };
  74140. return PolygonMeshBuilder;
  74141. }());
  74142. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  74143. })(BABYLON || (BABYLON = {}));
  74144. //# sourceMappingURL=babylon.polygonMesh.js.map
  74145. var BABYLON;
  74146. (function (BABYLON) {
  74147. // Unique ID when we import meshes from Babylon to CSG
  74148. var currentCSGMeshId = 0;
  74149. // # class Vertex
  74150. // Represents a vertex of a polygon. Use your own vertex class instead of this
  74151. // one to provide additional features like texture coordinates and vertex
  74152. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  74153. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  74154. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  74155. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  74156. // is not used anywhere else.
  74157. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  74158. var Vertex = /** @class */ (function () {
  74159. function Vertex(pos, normal, uv) {
  74160. this.pos = pos;
  74161. this.normal = normal;
  74162. this.uv = uv;
  74163. }
  74164. Vertex.prototype.clone = function () {
  74165. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  74166. };
  74167. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  74168. // orientation of a polygon is flipped.
  74169. Vertex.prototype.flip = function () {
  74170. this.normal = this.normal.scale(-1);
  74171. };
  74172. // Create a new vertex between this vertex and `other` by linearly
  74173. // interpolating all properties using a parameter of `t`. Subclasses should
  74174. // override this to interpolate additional properties.
  74175. Vertex.prototype.interpolate = function (other, t) {
  74176. 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));
  74177. };
  74178. return Vertex;
  74179. }());
  74180. // # class Plane
  74181. // Represents a plane in 3D space.
  74182. var Plane = /** @class */ (function () {
  74183. function Plane(normal, w) {
  74184. this.normal = normal;
  74185. this.w = w;
  74186. }
  74187. Plane.FromPoints = function (a, b, c) {
  74188. var v0 = c.subtract(a);
  74189. var v1 = b.subtract(a);
  74190. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  74191. return null;
  74192. }
  74193. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  74194. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  74195. };
  74196. Plane.prototype.clone = function () {
  74197. return new Plane(this.normal.clone(), this.w);
  74198. };
  74199. Plane.prototype.flip = function () {
  74200. this.normal.scaleInPlace(-1);
  74201. this.w = -this.w;
  74202. };
  74203. // Split `polygon` by this plane if needed, then put the polygon or polygon
  74204. // fragments in the appropriate lists. Coplanar polygons go into either
  74205. // `coplanarFront` or `coplanarBack` depending on their orientation with
  74206. // respect to this plane. Polygons in front or in back of this plane go into
  74207. // either `front` or `back`.
  74208. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  74209. var COPLANAR = 0;
  74210. var FRONT = 1;
  74211. var BACK = 2;
  74212. var SPANNING = 3;
  74213. // Classify each point as well as the entire polygon into one of the above
  74214. // four classes.
  74215. var polygonType = 0;
  74216. var types = [];
  74217. var i;
  74218. var t;
  74219. for (i = 0; i < polygon.vertices.length; i++) {
  74220. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  74221. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  74222. polygonType |= type;
  74223. types.push(type);
  74224. }
  74225. // Put the polygon in the correct list, splitting it when necessary.
  74226. switch (polygonType) {
  74227. case COPLANAR:
  74228. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  74229. break;
  74230. case FRONT:
  74231. front.push(polygon);
  74232. break;
  74233. case BACK:
  74234. back.push(polygon);
  74235. break;
  74236. case SPANNING:
  74237. var f = [], b = [];
  74238. for (i = 0; i < polygon.vertices.length; i++) {
  74239. var j = (i + 1) % polygon.vertices.length;
  74240. var ti = types[i], tj = types[j];
  74241. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  74242. if (ti !== BACK)
  74243. f.push(vi);
  74244. if (ti !== FRONT)
  74245. b.push(ti !== BACK ? vi.clone() : vi);
  74246. if ((ti | tj) === SPANNING) {
  74247. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  74248. var v = vi.interpolate(vj, t);
  74249. f.push(v);
  74250. b.push(v.clone());
  74251. }
  74252. }
  74253. var poly;
  74254. if (f.length >= 3) {
  74255. poly = new Polygon(f, polygon.shared);
  74256. if (poly.plane)
  74257. front.push(poly);
  74258. }
  74259. if (b.length >= 3) {
  74260. poly = new Polygon(b, polygon.shared);
  74261. if (poly.plane)
  74262. back.push(poly);
  74263. }
  74264. break;
  74265. }
  74266. };
  74267. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  74268. // point is on the plane.
  74269. Plane.EPSILON = 1e-5;
  74270. return Plane;
  74271. }());
  74272. // # class Polygon
  74273. // Represents a convex polygon. The vertices used to initialize a polygon must
  74274. // be coplanar and form a convex loop.
  74275. //
  74276. // Each convex polygon has a `shared` property, which is shared between all
  74277. // polygons that are clones of each other or were split from the same polygon.
  74278. // This can be used to define per-polygon properties (such as surface color).
  74279. var Polygon = /** @class */ (function () {
  74280. function Polygon(vertices, shared) {
  74281. this.vertices = vertices;
  74282. this.shared = shared;
  74283. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  74284. }
  74285. Polygon.prototype.clone = function () {
  74286. var vertices = this.vertices.map(function (v) { return v.clone(); });
  74287. return new Polygon(vertices, this.shared);
  74288. };
  74289. Polygon.prototype.flip = function () {
  74290. this.vertices.reverse().map(function (v) { v.flip(); });
  74291. this.plane.flip();
  74292. };
  74293. return Polygon;
  74294. }());
  74295. // # class Node
  74296. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  74297. // by picking a polygon to split along. That polygon (and all other coplanar
  74298. // polygons) are added directly to that node and the other polygons are added to
  74299. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  74300. // no distinction between internal and leaf nodes.
  74301. var Node = /** @class */ (function () {
  74302. function Node(polygons) {
  74303. this.plane = null;
  74304. this.front = null;
  74305. this.back = null;
  74306. this.polygons = new Array();
  74307. if (polygons) {
  74308. this.build(polygons);
  74309. }
  74310. }
  74311. Node.prototype.clone = function () {
  74312. var node = new Node();
  74313. node.plane = this.plane && this.plane.clone();
  74314. node.front = this.front && this.front.clone();
  74315. node.back = this.back && this.back.clone();
  74316. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  74317. return node;
  74318. };
  74319. // Convert solid space to empty space and empty space to solid space.
  74320. Node.prototype.invert = function () {
  74321. for (var i = 0; i < this.polygons.length; i++) {
  74322. this.polygons[i].flip();
  74323. }
  74324. if (this.plane) {
  74325. this.plane.flip();
  74326. }
  74327. if (this.front) {
  74328. this.front.invert();
  74329. }
  74330. if (this.back) {
  74331. this.back.invert();
  74332. }
  74333. var temp = this.front;
  74334. this.front = this.back;
  74335. this.back = temp;
  74336. };
  74337. // Recursively remove all polygons in `polygons` that are inside this BSP
  74338. // tree.
  74339. Node.prototype.clipPolygons = function (polygons) {
  74340. if (!this.plane)
  74341. return polygons.slice();
  74342. var front = new Array(), back = new Array();
  74343. for (var i = 0; i < polygons.length; i++) {
  74344. this.plane.splitPolygon(polygons[i], front, back, front, back);
  74345. }
  74346. if (this.front) {
  74347. front = this.front.clipPolygons(front);
  74348. }
  74349. if (this.back) {
  74350. back = this.back.clipPolygons(back);
  74351. }
  74352. else {
  74353. back = [];
  74354. }
  74355. return front.concat(back);
  74356. };
  74357. // Remove all polygons in this BSP tree that are inside the other BSP tree
  74358. // `bsp`.
  74359. Node.prototype.clipTo = function (bsp) {
  74360. this.polygons = bsp.clipPolygons(this.polygons);
  74361. if (this.front)
  74362. this.front.clipTo(bsp);
  74363. if (this.back)
  74364. this.back.clipTo(bsp);
  74365. };
  74366. // Return a list of all polygons in this BSP tree.
  74367. Node.prototype.allPolygons = function () {
  74368. var polygons = this.polygons.slice();
  74369. if (this.front)
  74370. polygons = polygons.concat(this.front.allPolygons());
  74371. if (this.back)
  74372. polygons = polygons.concat(this.back.allPolygons());
  74373. return polygons;
  74374. };
  74375. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  74376. // new polygons are filtered down to the bottom of the tree and become new
  74377. // nodes there. Each set of polygons is partitioned using the first polygon
  74378. // (no heuristic is used to pick a good split).
  74379. Node.prototype.build = function (polygons) {
  74380. if (!polygons.length)
  74381. return;
  74382. if (!this.plane)
  74383. this.plane = polygons[0].plane.clone();
  74384. var front = new Array(), back = new Array();
  74385. for (var i = 0; i < polygons.length; i++) {
  74386. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  74387. }
  74388. if (front.length) {
  74389. if (!this.front)
  74390. this.front = new Node();
  74391. this.front.build(front);
  74392. }
  74393. if (back.length) {
  74394. if (!this.back)
  74395. this.back = new Node();
  74396. this.back.build(back);
  74397. }
  74398. };
  74399. return Node;
  74400. }());
  74401. var CSG = /** @class */ (function () {
  74402. function CSG() {
  74403. this.polygons = new Array();
  74404. }
  74405. // Convert BABYLON.Mesh to BABYLON.CSG
  74406. CSG.FromMesh = function (mesh) {
  74407. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  74408. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  74409. if (mesh instanceof BABYLON.Mesh) {
  74410. mesh.computeWorldMatrix(true);
  74411. matrix = mesh.getWorldMatrix();
  74412. meshPosition = mesh.position.clone();
  74413. meshRotation = mesh.rotation.clone();
  74414. if (mesh.rotationQuaternion) {
  74415. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  74416. }
  74417. meshScaling = mesh.scaling.clone();
  74418. }
  74419. else {
  74420. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  74421. }
  74422. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  74423. var subMeshes = mesh.subMeshes;
  74424. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  74425. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  74426. vertices = [];
  74427. for (var j = 0; j < 3; j++) {
  74428. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  74429. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  74430. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  74431. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  74432. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  74433. vertex = new Vertex(position, normal, uv);
  74434. vertices.push(vertex);
  74435. }
  74436. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  74437. // To handle the case of degenerated triangle
  74438. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  74439. if (polygon.plane)
  74440. polygons.push(polygon);
  74441. }
  74442. }
  74443. var csg = CSG.FromPolygons(polygons);
  74444. csg.matrix = matrix;
  74445. csg.position = meshPosition;
  74446. csg.rotation = meshRotation;
  74447. csg.scaling = meshScaling;
  74448. csg.rotationQuaternion = meshRotationQuaternion;
  74449. currentCSGMeshId++;
  74450. return csg;
  74451. };
  74452. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  74453. CSG.FromPolygons = function (polygons) {
  74454. var csg = new CSG();
  74455. csg.polygons = polygons;
  74456. return csg;
  74457. };
  74458. CSG.prototype.clone = function () {
  74459. var csg = new CSG();
  74460. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  74461. csg.copyTransformAttributes(this);
  74462. return csg;
  74463. };
  74464. CSG.prototype.union = function (csg) {
  74465. var a = new Node(this.clone().polygons);
  74466. var b = new Node(csg.clone().polygons);
  74467. a.clipTo(b);
  74468. b.clipTo(a);
  74469. b.invert();
  74470. b.clipTo(a);
  74471. b.invert();
  74472. a.build(b.allPolygons());
  74473. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  74474. };
  74475. CSG.prototype.unionInPlace = function (csg) {
  74476. var a = new Node(this.polygons);
  74477. var b = new Node(csg.polygons);
  74478. a.clipTo(b);
  74479. b.clipTo(a);
  74480. b.invert();
  74481. b.clipTo(a);
  74482. b.invert();
  74483. a.build(b.allPolygons());
  74484. this.polygons = a.allPolygons();
  74485. };
  74486. CSG.prototype.subtract = function (csg) {
  74487. var a = new Node(this.clone().polygons);
  74488. var b = new Node(csg.clone().polygons);
  74489. a.invert();
  74490. a.clipTo(b);
  74491. b.clipTo(a);
  74492. b.invert();
  74493. b.clipTo(a);
  74494. b.invert();
  74495. a.build(b.allPolygons());
  74496. a.invert();
  74497. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  74498. };
  74499. CSG.prototype.subtractInPlace = function (csg) {
  74500. var a = new Node(this.polygons);
  74501. var b = new Node(csg.polygons);
  74502. a.invert();
  74503. a.clipTo(b);
  74504. b.clipTo(a);
  74505. b.invert();
  74506. b.clipTo(a);
  74507. b.invert();
  74508. a.build(b.allPolygons());
  74509. a.invert();
  74510. this.polygons = a.allPolygons();
  74511. };
  74512. CSG.prototype.intersect = function (csg) {
  74513. var a = new Node(this.clone().polygons);
  74514. var b = new Node(csg.clone().polygons);
  74515. a.invert();
  74516. b.clipTo(a);
  74517. b.invert();
  74518. a.clipTo(b);
  74519. b.clipTo(a);
  74520. a.build(b.allPolygons());
  74521. a.invert();
  74522. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  74523. };
  74524. CSG.prototype.intersectInPlace = function (csg) {
  74525. var a = new Node(this.polygons);
  74526. var b = new Node(csg.polygons);
  74527. a.invert();
  74528. b.clipTo(a);
  74529. b.invert();
  74530. a.clipTo(b);
  74531. b.clipTo(a);
  74532. a.build(b.allPolygons());
  74533. a.invert();
  74534. this.polygons = a.allPolygons();
  74535. };
  74536. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  74537. // not modified.
  74538. CSG.prototype.inverse = function () {
  74539. var csg = this.clone();
  74540. csg.inverseInPlace();
  74541. return csg;
  74542. };
  74543. CSG.prototype.inverseInPlace = function () {
  74544. this.polygons.map(function (p) { p.flip(); });
  74545. };
  74546. // This is used to keep meshes transformations so they can be restored
  74547. // when we build back a Babylon Mesh
  74548. // NB : All CSG operations are performed in world coordinates
  74549. CSG.prototype.copyTransformAttributes = function (csg) {
  74550. this.matrix = csg.matrix;
  74551. this.position = csg.position;
  74552. this.rotation = csg.rotation;
  74553. this.scaling = csg.scaling;
  74554. this.rotationQuaternion = csg.rotationQuaternion;
  74555. return this;
  74556. };
  74557. // Build Raw mesh from CSG
  74558. // Coordinates here are in world space
  74559. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  74560. var matrix = this.matrix.clone();
  74561. matrix.invert();
  74562. 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;
  74563. if (keepSubMeshes) {
  74564. // Sort Polygons, since subMeshes are indices range
  74565. polygons.sort(function (a, b) {
  74566. if (a.shared.meshId === b.shared.meshId) {
  74567. return a.shared.subMeshId - b.shared.subMeshId;
  74568. }
  74569. else {
  74570. return a.shared.meshId - b.shared.meshId;
  74571. }
  74572. });
  74573. }
  74574. for (var i = 0, il = polygons.length; i < il; i++) {
  74575. polygon = polygons[i];
  74576. // Building SubMeshes
  74577. if (!subMesh_dict[polygon.shared.meshId]) {
  74578. subMesh_dict[polygon.shared.meshId] = {};
  74579. }
  74580. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  74581. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  74582. indexStart: +Infinity,
  74583. indexEnd: -Infinity,
  74584. materialIndex: polygon.shared.materialIndex
  74585. };
  74586. }
  74587. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  74588. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  74589. polygonIndices[0] = 0;
  74590. polygonIndices[1] = j - 1;
  74591. polygonIndices[2] = j;
  74592. for (var k = 0; k < 3; k++) {
  74593. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  74594. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  74595. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  74596. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  74597. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  74598. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  74599. // Check if 2 points can be merged
  74600. if (!(typeof vertex_idx !== 'undefined' &&
  74601. normals[vertex_idx * 3] === localNormal.x &&
  74602. normals[vertex_idx * 3 + 1] === localNormal.y &&
  74603. normals[vertex_idx * 3 + 2] === localNormal.z &&
  74604. uvs[vertex_idx * 2] === uv.x &&
  74605. uvs[vertex_idx * 2 + 1] === uv.y)) {
  74606. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  74607. uvs.push(uv.x, uv.y);
  74608. normals.push(normal.x, normal.y, normal.z);
  74609. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  74610. }
  74611. indices.push(vertex_idx);
  74612. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  74613. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  74614. currentIndex++;
  74615. }
  74616. }
  74617. }
  74618. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  74619. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  74620. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  74621. mesh.setIndices(indices, null);
  74622. if (keepSubMeshes) {
  74623. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  74624. var materialIndexOffset = 0, materialMaxIndex;
  74625. mesh.subMeshes = new Array();
  74626. for (var m in subMesh_dict) {
  74627. materialMaxIndex = -1;
  74628. for (var sm in subMesh_dict[m]) {
  74629. subMesh_obj = subMesh_dict[m][sm];
  74630. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  74631. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  74632. }
  74633. materialIndexOffset += ++materialMaxIndex;
  74634. }
  74635. }
  74636. return mesh;
  74637. };
  74638. // Build Mesh from CSG taking material and transforms into account
  74639. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  74640. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  74641. mesh.material = material;
  74642. mesh.position.copyFrom(this.position);
  74643. mesh.rotation.copyFrom(this.rotation);
  74644. if (this.rotationQuaternion) {
  74645. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  74646. }
  74647. mesh.scaling.copyFrom(this.scaling);
  74648. mesh.computeWorldMatrix(true);
  74649. return mesh;
  74650. };
  74651. return CSG;
  74652. }());
  74653. BABYLON.CSG = CSG;
  74654. })(BABYLON || (BABYLON = {}));
  74655. //# sourceMappingURL=babylon.csg.js.map
  74656. var BABYLON;
  74657. (function (BABYLON) {
  74658. var LensFlare = /** @class */ (function () {
  74659. function LensFlare(size, position, color, imgUrl, system) {
  74660. this.size = size;
  74661. this.position = position;
  74662. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  74663. this.color = color || new BABYLON.Color3(1, 1, 1);
  74664. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  74665. this._system = system;
  74666. system.lensFlares.push(this);
  74667. }
  74668. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  74669. return new LensFlare(size, position, color, imgUrl, system);
  74670. };
  74671. LensFlare.prototype.dispose = function () {
  74672. if (this.texture) {
  74673. this.texture.dispose();
  74674. }
  74675. // Remove from scene
  74676. var index = this._system.lensFlares.indexOf(this);
  74677. this._system.lensFlares.splice(index, 1);
  74678. };
  74679. ;
  74680. return LensFlare;
  74681. }());
  74682. BABYLON.LensFlare = LensFlare;
  74683. })(BABYLON || (BABYLON = {}));
  74684. //# sourceMappingURL=babylon.lensFlare.js.map
  74685. var BABYLON;
  74686. (function (BABYLON) {
  74687. var LensFlareSystem = /** @class */ (function () {
  74688. function LensFlareSystem(name, emitter, scene) {
  74689. this.name = name;
  74690. this.lensFlares = new Array();
  74691. this.borderLimit = 300;
  74692. this.viewportBorder = 0;
  74693. this.layerMask = 0x0FFFFFFF;
  74694. this._vertexBuffers = {};
  74695. this._isEnabled = true;
  74696. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  74697. this._emitter = emitter;
  74698. this.id = name;
  74699. scene.lensFlareSystems.push(this);
  74700. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  74701. var engine = scene.getEngine();
  74702. // VBO
  74703. var vertices = [];
  74704. vertices.push(1, 1);
  74705. vertices.push(-1, 1);
  74706. vertices.push(-1, -1);
  74707. vertices.push(1, -1);
  74708. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  74709. // Indices
  74710. var indices = [];
  74711. indices.push(0);
  74712. indices.push(1);
  74713. indices.push(2);
  74714. indices.push(0);
  74715. indices.push(2);
  74716. indices.push(3);
  74717. this._indexBuffer = engine.createIndexBuffer(indices);
  74718. // Effects
  74719. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  74720. }
  74721. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  74722. get: function () {
  74723. return this._isEnabled;
  74724. },
  74725. set: function (value) {
  74726. this._isEnabled = value;
  74727. },
  74728. enumerable: true,
  74729. configurable: true
  74730. });
  74731. LensFlareSystem.prototype.getScene = function () {
  74732. return this._scene;
  74733. };
  74734. LensFlareSystem.prototype.getEmitter = function () {
  74735. return this._emitter;
  74736. };
  74737. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  74738. this._emitter = newEmitter;
  74739. };
  74740. LensFlareSystem.prototype.getEmitterPosition = function () {
  74741. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  74742. };
  74743. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  74744. var position = this.getEmitterPosition();
  74745. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  74746. this._positionX = position.x;
  74747. this._positionY = position.y;
  74748. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  74749. if (this.viewportBorder > 0) {
  74750. globalViewport.x -= this.viewportBorder;
  74751. globalViewport.y -= this.viewportBorder;
  74752. globalViewport.width += this.viewportBorder * 2;
  74753. globalViewport.height += this.viewportBorder * 2;
  74754. position.x += this.viewportBorder;
  74755. position.y += this.viewportBorder;
  74756. this._positionX += this.viewportBorder;
  74757. this._positionY += this.viewportBorder;
  74758. }
  74759. if (position.z > 0) {
  74760. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  74761. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  74762. return true;
  74763. }
  74764. return true;
  74765. }
  74766. return false;
  74767. };
  74768. LensFlareSystem.prototype._isVisible = function () {
  74769. if (!this._isEnabled || !this._scene.activeCamera) {
  74770. return false;
  74771. }
  74772. var emitterPosition = this.getEmitterPosition();
  74773. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  74774. var distance = direction.length();
  74775. direction.normalize();
  74776. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  74777. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  74778. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  74779. };
  74780. LensFlareSystem.prototype.render = function () {
  74781. if (!this._effect.isReady() || !this._scene.activeCamera)
  74782. return false;
  74783. var engine = this._scene.getEngine();
  74784. var viewport = this._scene.activeCamera.viewport;
  74785. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  74786. // Position
  74787. if (!this.computeEffectivePosition(globalViewport)) {
  74788. return false;
  74789. }
  74790. // Visibility
  74791. if (!this._isVisible()) {
  74792. return false;
  74793. }
  74794. // Intensity
  74795. var awayX;
  74796. var awayY;
  74797. if (this._positionX < this.borderLimit + globalViewport.x) {
  74798. awayX = this.borderLimit + globalViewport.x - this._positionX;
  74799. }
  74800. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  74801. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  74802. }
  74803. else {
  74804. awayX = 0;
  74805. }
  74806. if (this._positionY < this.borderLimit + globalViewport.y) {
  74807. awayY = this.borderLimit + globalViewport.y - this._positionY;
  74808. }
  74809. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  74810. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  74811. }
  74812. else {
  74813. awayY = 0;
  74814. }
  74815. var away = (awayX > awayY) ? awayX : awayY;
  74816. away -= this.viewportBorder;
  74817. if (away > this.borderLimit) {
  74818. away = this.borderLimit;
  74819. }
  74820. var intensity = 1.0 - (away / this.borderLimit);
  74821. if (intensity < 0) {
  74822. return false;
  74823. }
  74824. if (intensity > 1.0) {
  74825. intensity = 1.0;
  74826. }
  74827. if (this.viewportBorder > 0) {
  74828. globalViewport.x += this.viewportBorder;
  74829. globalViewport.y += this.viewportBorder;
  74830. globalViewport.width -= this.viewportBorder * 2;
  74831. globalViewport.height -= this.viewportBorder * 2;
  74832. this._positionX -= this.viewportBorder;
  74833. this._positionY -= this.viewportBorder;
  74834. }
  74835. // Position
  74836. var centerX = globalViewport.x + globalViewport.width / 2;
  74837. var centerY = globalViewport.y + globalViewport.height / 2;
  74838. var distX = centerX - this._positionX;
  74839. var distY = centerY - this._positionY;
  74840. // Effects
  74841. engine.enableEffect(this._effect);
  74842. engine.setState(false);
  74843. engine.setDepthBuffer(false);
  74844. // VBOs
  74845. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  74846. // Flares
  74847. for (var index = 0; index < this.lensFlares.length; index++) {
  74848. var flare = this.lensFlares[index];
  74849. engine.setAlphaMode(flare.alphaMode);
  74850. var x = centerX - (distX * flare.position);
  74851. var y = centerY - (distY * flare.position);
  74852. var cw = flare.size;
  74853. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  74854. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  74855. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  74856. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  74857. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  74858. // Texture
  74859. this._effect.setTexture("textureSampler", flare.texture);
  74860. // Color
  74861. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  74862. // Draw order
  74863. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  74864. }
  74865. engine.setDepthBuffer(true);
  74866. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  74867. return true;
  74868. };
  74869. LensFlareSystem.prototype.dispose = function () {
  74870. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74871. if (vertexBuffer) {
  74872. vertexBuffer.dispose();
  74873. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  74874. }
  74875. if (this._indexBuffer) {
  74876. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  74877. this._indexBuffer = null;
  74878. }
  74879. while (this.lensFlares.length) {
  74880. this.lensFlares[0].dispose();
  74881. }
  74882. // Remove from scene
  74883. var index = this._scene.lensFlareSystems.indexOf(this);
  74884. this._scene.lensFlareSystems.splice(index, 1);
  74885. };
  74886. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  74887. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  74888. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  74889. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  74890. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  74891. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  74892. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  74893. var parsedFlare = parsedLensFlareSystem.flares[index];
  74894. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  74895. }
  74896. return lensFlareSystem;
  74897. };
  74898. LensFlareSystem.prototype.serialize = function () {
  74899. var serializationObject = {};
  74900. serializationObject.id = this.id;
  74901. serializationObject.name = this.name;
  74902. serializationObject.emitterId = this.getEmitter().id;
  74903. serializationObject.borderLimit = this.borderLimit;
  74904. serializationObject.flares = [];
  74905. for (var index = 0; index < this.lensFlares.length; index++) {
  74906. var flare = this.lensFlares[index];
  74907. serializationObject.flares.push({
  74908. size: flare.size,
  74909. position: flare.position,
  74910. color: flare.color.asArray(),
  74911. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  74912. });
  74913. }
  74914. return serializationObject;
  74915. };
  74916. return LensFlareSystem;
  74917. }());
  74918. BABYLON.LensFlareSystem = LensFlareSystem;
  74919. })(BABYLON || (BABYLON = {}));
  74920. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  74921. var BABYLON;
  74922. (function (BABYLON) {
  74923. /**
  74924. * This is a holder class for the physics joint created by the physics plugin.
  74925. * It holds a set of functions to control the underlying joint.
  74926. */
  74927. var PhysicsJoint = /** @class */ (function () {
  74928. function PhysicsJoint(type, jointData) {
  74929. this.type = type;
  74930. this.jointData = jointData;
  74931. jointData.nativeParams = jointData.nativeParams || {};
  74932. }
  74933. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  74934. get: function () {
  74935. return this._physicsJoint;
  74936. },
  74937. set: function (newJoint) {
  74938. if (this._physicsJoint) {
  74939. //remove from the wolrd
  74940. }
  74941. this._physicsJoint = newJoint;
  74942. },
  74943. enumerable: true,
  74944. configurable: true
  74945. });
  74946. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  74947. set: function (physicsPlugin) {
  74948. this._physicsPlugin = physicsPlugin;
  74949. },
  74950. enumerable: true,
  74951. configurable: true
  74952. });
  74953. /**
  74954. * Execute a function that is physics-plugin specific.
  74955. * @param {Function} func the function that will be executed.
  74956. * It accepts two parameters: the physics world and the physics joint.
  74957. */
  74958. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  74959. func(this._physicsPlugin.world, this._physicsJoint);
  74960. };
  74961. //TODO check if the native joints are the same
  74962. //Joint Types
  74963. PhysicsJoint.DistanceJoint = 0;
  74964. PhysicsJoint.HingeJoint = 1;
  74965. PhysicsJoint.BallAndSocketJoint = 2;
  74966. PhysicsJoint.WheelJoint = 3;
  74967. PhysicsJoint.SliderJoint = 4;
  74968. //OIMO
  74969. PhysicsJoint.PrismaticJoint = 5;
  74970. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  74971. PhysicsJoint.UniversalJoint = 6;
  74972. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  74973. //Cannon
  74974. //Similar to a Ball-Joint. Different in params
  74975. PhysicsJoint.PointToPointJoint = 8;
  74976. //Cannon only at the moment
  74977. PhysicsJoint.SpringJoint = 9;
  74978. PhysicsJoint.LockJoint = 10;
  74979. return PhysicsJoint;
  74980. }());
  74981. BABYLON.PhysicsJoint = PhysicsJoint;
  74982. /**
  74983. * A class representing a physics distance joint.
  74984. */
  74985. var DistanceJoint = /** @class */ (function (_super) {
  74986. __extends(DistanceJoint, _super);
  74987. function DistanceJoint(jointData) {
  74988. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  74989. }
  74990. /**
  74991. * Update the predefined distance.
  74992. */
  74993. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  74994. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  74995. };
  74996. return DistanceJoint;
  74997. }(PhysicsJoint));
  74998. BABYLON.DistanceJoint = DistanceJoint;
  74999. var MotorEnabledJoint = /** @class */ (function (_super) {
  75000. __extends(MotorEnabledJoint, _super);
  75001. function MotorEnabledJoint(type, jointData) {
  75002. return _super.call(this, type, jointData) || this;
  75003. }
  75004. /**
  75005. * Set the motor values.
  75006. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75007. * @param {number} force the force to apply
  75008. * @param {number} maxForce max force for this motor.
  75009. */
  75010. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  75011. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  75012. };
  75013. /**
  75014. * Set the motor's limits.
  75015. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75016. */
  75017. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  75018. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  75019. };
  75020. return MotorEnabledJoint;
  75021. }(PhysicsJoint));
  75022. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  75023. /**
  75024. * This class represents a single hinge physics joint
  75025. */
  75026. var HingeJoint = /** @class */ (function (_super) {
  75027. __extends(HingeJoint, _super);
  75028. function HingeJoint(jointData) {
  75029. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  75030. }
  75031. /**
  75032. * Set the motor values.
  75033. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75034. * @param {number} force the force to apply
  75035. * @param {number} maxForce max force for this motor.
  75036. */
  75037. HingeJoint.prototype.setMotor = function (force, maxForce) {
  75038. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  75039. };
  75040. /**
  75041. * Set the motor's limits.
  75042. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75043. */
  75044. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  75045. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  75046. };
  75047. return HingeJoint;
  75048. }(MotorEnabledJoint));
  75049. BABYLON.HingeJoint = HingeJoint;
  75050. /**
  75051. * This class represents a dual hinge physics joint (same as wheel joint)
  75052. */
  75053. var Hinge2Joint = /** @class */ (function (_super) {
  75054. __extends(Hinge2Joint, _super);
  75055. function Hinge2Joint(jointData) {
  75056. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  75057. }
  75058. /**
  75059. * Set the motor values.
  75060. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75061. * @param {number} force the force to apply
  75062. * @param {number} maxForce max force for this motor.
  75063. * @param {motorIndex} the motor's index, 0 or 1.
  75064. */
  75065. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  75066. if (motorIndex === void 0) { motorIndex = 0; }
  75067. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  75068. };
  75069. /**
  75070. * Set the motor limits.
  75071. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75072. * @param {number} upperLimit the upper limit
  75073. * @param {number} lowerLimit lower limit
  75074. * @param {motorIndex} the motor's index, 0 or 1.
  75075. */
  75076. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  75077. if (motorIndex === void 0) { motorIndex = 0; }
  75078. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  75079. };
  75080. return Hinge2Joint;
  75081. }(MotorEnabledJoint));
  75082. BABYLON.Hinge2Joint = Hinge2Joint;
  75083. })(BABYLON || (BABYLON = {}));
  75084. //# sourceMappingURL=babylon.physicsJoint.js.map
  75085. var BABYLON;
  75086. (function (BABYLON) {
  75087. var PhysicsImpostor = /** @class */ (function () {
  75088. function PhysicsImpostor(object, type, _options, _scene) {
  75089. if (_options === void 0) { _options = { mass: 0 }; }
  75090. var _this = this;
  75091. this.object = object;
  75092. this.type = type;
  75093. this._options = _options;
  75094. this._scene = _scene;
  75095. this._bodyUpdateRequired = false;
  75096. this._onBeforePhysicsStepCallbacks = new Array();
  75097. this._onAfterPhysicsStepCallbacks = new Array();
  75098. this._onPhysicsCollideCallbacks = [];
  75099. this._deltaPosition = BABYLON.Vector3.Zero();
  75100. this._isDisposed = false;
  75101. //temp variables for parent rotation calculations
  75102. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  75103. this._tmpQuat = new BABYLON.Quaternion();
  75104. this._tmpQuat2 = new BABYLON.Quaternion();
  75105. /**
  75106. * this function is executed by the physics engine.
  75107. */
  75108. this.beforeStep = function () {
  75109. if (!_this._physicsEngine) {
  75110. return;
  75111. }
  75112. _this.object.translate(_this._deltaPosition, -1);
  75113. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  75114. _this.object.computeWorldMatrix(false);
  75115. if (_this.object.parent && _this.object.rotationQuaternion) {
  75116. _this.getParentsRotation();
  75117. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  75118. }
  75119. else {
  75120. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  75121. }
  75122. if (!_this._options.disableBidirectionalTransformation) {
  75123. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  75124. }
  75125. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  75126. func(_this);
  75127. });
  75128. };
  75129. /**
  75130. * this function is executed by the physics engine.
  75131. */
  75132. this.afterStep = function () {
  75133. if (!_this._physicsEngine) {
  75134. return;
  75135. }
  75136. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  75137. func(_this);
  75138. });
  75139. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  75140. // object has now its world rotation. needs to be converted to local.
  75141. if (_this.object.parent && _this.object.rotationQuaternion) {
  75142. _this.getParentsRotation();
  75143. _this._tmpQuat.conjugateInPlace();
  75144. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  75145. }
  75146. // take the position set and make it the absolute position of this object.
  75147. _this.object.setAbsolutePosition(_this.object.position);
  75148. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  75149. _this.object.translate(_this._deltaPosition, 1);
  75150. };
  75151. /**
  75152. * Legacy collision detection event support
  75153. */
  75154. this.onCollideEvent = null;
  75155. //event and body object due to cannon's event-based architecture.
  75156. this.onCollide = function (e) {
  75157. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  75158. return;
  75159. }
  75160. if (!_this._physicsEngine) {
  75161. return;
  75162. }
  75163. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  75164. if (otherImpostor) {
  75165. // Legacy collision detection event support
  75166. if (_this.onCollideEvent) {
  75167. _this.onCollideEvent(_this, otherImpostor);
  75168. }
  75169. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  75170. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  75171. }).forEach(function (obj) {
  75172. obj.callback(_this, otherImpostor);
  75173. });
  75174. }
  75175. };
  75176. //sanity check!
  75177. if (!this.object) {
  75178. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  75179. return;
  75180. }
  75181. //legacy support for old syntax.
  75182. if (!this._scene && object.getScene) {
  75183. this._scene = object.getScene();
  75184. }
  75185. if (!this._scene) {
  75186. return;
  75187. }
  75188. this._physicsEngine = this._scene.getPhysicsEngine();
  75189. if (!this._physicsEngine) {
  75190. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  75191. }
  75192. else {
  75193. //set the object's quaternion, if not set
  75194. if (!this.object.rotationQuaternion) {
  75195. if (this.object.rotation) {
  75196. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  75197. }
  75198. else {
  75199. this.object.rotationQuaternion = new BABYLON.Quaternion();
  75200. }
  75201. }
  75202. //default options params
  75203. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  75204. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  75205. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  75206. this._joints = [];
  75207. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  75208. if (!this.object.parent || this._options.ignoreParent) {
  75209. this._init();
  75210. }
  75211. else if (this.object.parent.physicsImpostor) {
  75212. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  75213. }
  75214. }
  75215. }
  75216. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  75217. get: function () {
  75218. return this._isDisposed;
  75219. },
  75220. enumerable: true,
  75221. configurable: true
  75222. });
  75223. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  75224. get: function () {
  75225. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  75226. },
  75227. set: function (value) {
  75228. this.setMass(value);
  75229. },
  75230. enumerable: true,
  75231. configurable: true
  75232. });
  75233. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  75234. get: function () {
  75235. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  75236. },
  75237. set: function (value) {
  75238. if (!this._physicsEngine) {
  75239. return;
  75240. }
  75241. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  75242. },
  75243. enumerable: true,
  75244. configurable: true
  75245. });
  75246. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  75247. get: function () {
  75248. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  75249. },
  75250. set: function (value) {
  75251. if (!this._physicsEngine) {
  75252. return;
  75253. }
  75254. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  75255. },
  75256. enumerable: true,
  75257. configurable: true
  75258. });
  75259. /**
  75260. * This function will completly initialize this impostor.
  75261. * It will create a new body - but only if this mesh has no parent.
  75262. * If it has, this impostor will not be used other than to define the impostor
  75263. * of the child mesh.
  75264. */
  75265. PhysicsImpostor.prototype._init = function () {
  75266. if (!this._physicsEngine) {
  75267. return;
  75268. }
  75269. this._physicsEngine.removeImpostor(this);
  75270. this.physicsBody = null;
  75271. this._parent = this._parent || this._getPhysicsParent();
  75272. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  75273. this._physicsEngine.addImpostor(this);
  75274. }
  75275. };
  75276. PhysicsImpostor.prototype._getPhysicsParent = function () {
  75277. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  75278. var parentMesh = this.object.parent;
  75279. return parentMesh.physicsImpostor;
  75280. }
  75281. return null;
  75282. };
  75283. /**
  75284. * Should a new body be generated.
  75285. */
  75286. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  75287. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  75288. };
  75289. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  75290. this.forceUpdate();
  75291. };
  75292. /**
  75293. * Force a regeneration of this or the parent's impostor's body.
  75294. * Use under cautious - This will remove all joints already implemented.
  75295. */
  75296. PhysicsImpostor.prototype.forceUpdate = function () {
  75297. this._init();
  75298. if (this.parent && !this._options.ignoreParent) {
  75299. this.parent.forceUpdate();
  75300. }
  75301. };
  75302. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  75303. /*public get mesh(): AbstractMesh {
  75304. return this._mesh;
  75305. }*/
  75306. /**
  75307. * Gets the body that holds this impostor. Either its own, or its parent.
  75308. */
  75309. get: function () {
  75310. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  75311. },
  75312. /**
  75313. * Set the physics body. Used mainly by the physics engine/plugin
  75314. */
  75315. set: function (physicsBody) {
  75316. if (this._physicsBody && this._physicsEngine) {
  75317. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  75318. }
  75319. this._physicsBody = physicsBody;
  75320. this.resetUpdateFlags();
  75321. },
  75322. enumerable: true,
  75323. configurable: true
  75324. });
  75325. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  75326. get: function () {
  75327. return !this._options.ignoreParent && this._parent ? this._parent : null;
  75328. },
  75329. set: function (value) {
  75330. this._parent = value;
  75331. },
  75332. enumerable: true,
  75333. configurable: true
  75334. });
  75335. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  75336. this._bodyUpdateRequired = false;
  75337. };
  75338. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  75339. if (this.object.getBoundingInfo) {
  75340. var q = this.object.rotationQuaternion;
  75341. //reset rotation
  75342. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  75343. //calculate the world matrix with no rotation
  75344. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  75345. var boundingInfo = this.object.getBoundingInfo();
  75346. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  75347. //bring back the rotation
  75348. this.object.rotationQuaternion = q;
  75349. //calculate the world matrix with the new rotation
  75350. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  75351. return size;
  75352. }
  75353. else {
  75354. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  75355. }
  75356. };
  75357. PhysicsImpostor.prototype.getObjectCenter = function () {
  75358. if (this.object.getBoundingInfo) {
  75359. var boundingInfo = this.object.getBoundingInfo();
  75360. return boundingInfo.boundingBox.centerWorld;
  75361. }
  75362. else {
  75363. return this.object.position;
  75364. }
  75365. };
  75366. /**
  75367. * Get a specific parametes from the options parameter.
  75368. */
  75369. PhysicsImpostor.prototype.getParam = function (paramName) {
  75370. return this._options[paramName];
  75371. };
  75372. /**
  75373. * Sets a specific parameter in the options given to the physics plugin
  75374. */
  75375. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  75376. this._options[paramName] = value;
  75377. this._bodyUpdateRequired = true;
  75378. };
  75379. /**
  75380. * Specifically change the body's mass option. Won't recreate the physics body object
  75381. */
  75382. PhysicsImpostor.prototype.setMass = function (mass) {
  75383. if (this.getParam("mass") !== mass) {
  75384. this.setParam("mass", mass);
  75385. }
  75386. if (this._physicsEngine) {
  75387. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  75388. }
  75389. };
  75390. PhysicsImpostor.prototype.getLinearVelocity = function () {
  75391. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  75392. };
  75393. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  75394. if (this._physicsEngine) {
  75395. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  75396. }
  75397. };
  75398. PhysicsImpostor.prototype.getAngularVelocity = function () {
  75399. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  75400. };
  75401. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  75402. if (this._physicsEngine) {
  75403. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  75404. }
  75405. };
  75406. /**
  75407. * Execute a function with the physics plugin native code.
  75408. * Provide a function the will have two variables - the world object and the physics body object.
  75409. */
  75410. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  75411. if (this._physicsEngine) {
  75412. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  75413. }
  75414. };
  75415. /**
  75416. * Register a function that will be executed before the physics world is stepping forward.
  75417. */
  75418. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  75419. this._onBeforePhysicsStepCallbacks.push(func);
  75420. };
  75421. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  75422. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  75423. if (index > -1) {
  75424. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  75425. }
  75426. else {
  75427. BABYLON.Tools.Warn("Function to remove was not found");
  75428. }
  75429. };
  75430. /**
  75431. * Register a function that will be executed after the physics step
  75432. */
  75433. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  75434. this._onAfterPhysicsStepCallbacks.push(func);
  75435. };
  75436. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  75437. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  75438. if (index > -1) {
  75439. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  75440. }
  75441. else {
  75442. BABYLON.Tools.Warn("Function to remove was not found");
  75443. }
  75444. };
  75445. /**
  75446. * register a function that will be executed when this impostor collides against a different body.
  75447. */
  75448. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  75449. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  75450. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  75451. };
  75452. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  75453. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  75454. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  75455. if (index > -1) {
  75456. this._onPhysicsCollideCallbacks.splice(index, 1);
  75457. }
  75458. else {
  75459. BABYLON.Tools.Warn("Function to remove was not found");
  75460. }
  75461. };
  75462. PhysicsImpostor.prototype.getParentsRotation = function () {
  75463. var parent = this.object.parent;
  75464. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  75465. while (parent) {
  75466. if (parent.rotationQuaternion) {
  75467. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  75468. }
  75469. else {
  75470. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  75471. }
  75472. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  75473. parent = parent.parent;
  75474. }
  75475. return this._tmpQuat;
  75476. };
  75477. /**
  75478. * Apply a force
  75479. */
  75480. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  75481. if (this._physicsEngine) {
  75482. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  75483. }
  75484. return this;
  75485. };
  75486. /**
  75487. * Apply an impulse
  75488. */
  75489. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  75490. if (this._physicsEngine) {
  75491. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  75492. }
  75493. return this;
  75494. };
  75495. /**
  75496. * A help function to create a joint.
  75497. */
  75498. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  75499. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  75500. this.addJoint(otherImpostor, joint);
  75501. return this;
  75502. };
  75503. /**
  75504. * Add a joint to this impostor with a different impostor.
  75505. */
  75506. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  75507. this._joints.push({
  75508. otherImpostor: otherImpostor,
  75509. joint: joint
  75510. });
  75511. if (this._physicsEngine) {
  75512. this._physicsEngine.addJoint(this, otherImpostor, joint);
  75513. }
  75514. return this;
  75515. };
  75516. /**
  75517. * Will keep this body still, in a sleep mode.
  75518. */
  75519. PhysicsImpostor.prototype.sleep = function () {
  75520. if (this._physicsEngine) {
  75521. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  75522. }
  75523. return this;
  75524. };
  75525. /**
  75526. * Wake the body up.
  75527. */
  75528. PhysicsImpostor.prototype.wakeUp = function () {
  75529. if (this._physicsEngine) {
  75530. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  75531. }
  75532. return this;
  75533. };
  75534. PhysicsImpostor.prototype.clone = function (newObject) {
  75535. if (!newObject)
  75536. return null;
  75537. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  75538. };
  75539. PhysicsImpostor.prototype.dispose = function () {
  75540. var _this = this;
  75541. //no dispose if no physics engine is available.
  75542. if (!this._physicsEngine) {
  75543. return;
  75544. }
  75545. this._joints.forEach(function (j) {
  75546. if (_this._physicsEngine) {
  75547. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  75548. }
  75549. });
  75550. //dispose the physics body
  75551. this._physicsEngine.removeImpostor(this);
  75552. if (this.parent) {
  75553. this.parent.forceUpdate();
  75554. }
  75555. else {
  75556. /*this._object.getChildMeshes().forEach(function(mesh) {
  75557. if (mesh.physicsImpostor) {
  75558. if (disposeChildren) {
  75559. mesh.physicsImpostor.dispose();
  75560. mesh.physicsImpostor = null;
  75561. }
  75562. }
  75563. })*/
  75564. }
  75565. this._isDisposed = true;
  75566. };
  75567. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  75568. this._deltaPosition.copyFrom(position);
  75569. };
  75570. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  75571. if (!this._deltaRotation) {
  75572. this._deltaRotation = new BABYLON.Quaternion();
  75573. }
  75574. this._deltaRotation.copyFrom(rotation);
  75575. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  75576. };
  75577. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  75578. if (this._physicsEngine) {
  75579. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  75580. }
  75581. return this;
  75582. };
  75583. PhysicsImpostor.prototype.getRadius = function () {
  75584. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  75585. };
  75586. /**
  75587. * Sync a bone with this impostor
  75588. * @param bone The bone to sync to the impostor.
  75589. * @param boneMesh The mesh that the bone is influencing.
  75590. * @param jointPivot The pivot of the joint / bone in local space.
  75591. * @param distToJoint Optional distance from the impostor to the joint.
  75592. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  75593. */
  75594. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  75595. var tempVec = PhysicsImpostor._tmpVecs[0];
  75596. var mesh = this.object;
  75597. if (mesh.rotationQuaternion) {
  75598. if (adjustRotation) {
  75599. var tempQuat = PhysicsImpostor._tmpQuat;
  75600. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  75601. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  75602. }
  75603. else {
  75604. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  75605. }
  75606. }
  75607. tempVec.x = 0;
  75608. tempVec.y = 0;
  75609. tempVec.z = 0;
  75610. if (jointPivot) {
  75611. tempVec.x = jointPivot.x;
  75612. tempVec.y = jointPivot.y;
  75613. tempVec.z = jointPivot.z;
  75614. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  75615. if (distToJoint === undefined || distToJoint === null) {
  75616. distToJoint = jointPivot.length();
  75617. }
  75618. tempVec.x *= distToJoint;
  75619. tempVec.y *= distToJoint;
  75620. tempVec.z *= distToJoint;
  75621. }
  75622. if (bone.getParent()) {
  75623. tempVec.addInPlace(mesh.getAbsolutePosition());
  75624. bone.setAbsolutePosition(tempVec, boneMesh);
  75625. }
  75626. else {
  75627. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  75628. boneMesh.position.x -= tempVec.x;
  75629. boneMesh.position.y -= tempVec.y;
  75630. boneMesh.position.z -= tempVec.z;
  75631. }
  75632. };
  75633. /**
  75634. * Sync impostor to a bone
  75635. * @param bone The bone that the impostor will be synced to.
  75636. * @param boneMesh The mesh that the bone is influencing.
  75637. * @param jointPivot The pivot of the joint / bone in local space.
  75638. * @param distToJoint Optional distance from the impostor to the joint.
  75639. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  75640. * @param boneAxis Optional vector3 axis the bone is aligned with
  75641. */
  75642. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  75643. var mesh = this.object;
  75644. if (mesh.rotationQuaternion) {
  75645. if (adjustRotation) {
  75646. var tempQuat = PhysicsImpostor._tmpQuat;
  75647. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  75648. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  75649. }
  75650. else {
  75651. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  75652. }
  75653. }
  75654. var pos = PhysicsImpostor._tmpVecs[0];
  75655. var boneDir = PhysicsImpostor._tmpVecs[1];
  75656. if (!boneAxis) {
  75657. boneAxis = PhysicsImpostor._tmpVecs[2];
  75658. boneAxis.x = 0;
  75659. boneAxis.y = 1;
  75660. boneAxis.z = 0;
  75661. }
  75662. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  75663. bone.getAbsolutePositionToRef(boneMesh, pos);
  75664. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  75665. distToJoint = jointPivot.length();
  75666. }
  75667. if (distToJoint !== undefined && distToJoint !== null) {
  75668. pos.x += boneDir.x * distToJoint;
  75669. pos.y += boneDir.y * distToJoint;
  75670. pos.z += boneDir.z * distToJoint;
  75671. }
  75672. mesh.setAbsolutePosition(pos);
  75673. };
  75674. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  75675. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  75676. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  75677. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  75678. //Impostor types
  75679. PhysicsImpostor.NoImpostor = 0;
  75680. PhysicsImpostor.SphereImpostor = 1;
  75681. PhysicsImpostor.BoxImpostor = 2;
  75682. PhysicsImpostor.PlaneImpostor = 3;
  75683. PhysicsImpostor.MeshImpostor = 4;
  75684. PhysicsImpostor.CylinderImpostor = 7;
  75685. PhysicsImpostor.ParticleImpostor = 8;
  75686. PhysicsImpostor.HeightmapImpostor = 9;
  75687. return PhysicsImpostor;
  75688. }());
  75689. BABYLON.PhysicsImpostor = PhysicsImpostor;
  75690. })(BABYLON || (BABYLON = {}));
  75691. //# sourceMappingURL=babylon.physicsImpostor.js.map
  75692. var BABYLON;
  75693. (function (BABYLON) {
  75694. var PhysicsEngine = /** @class */ (function () {
  75695. function PhysicsEngine(gravity, _physicsPlugin) {
  75696. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  75697. this._physicsPlugin = _physicsPlugin;
  75698. //new methods and parameters
  75699. this._impostors = [];
  75700. this._joints = [];
  75701. if (!this._physicsPlugin.isSupported()) {
  75702. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  75703. + "Please make sure it is included.");
  75704. }
  75705. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  75706. this.setGravity(gravity);
  75707. this.setTimeStep();
  75708. }
  75709. PhysicsEngine.prototype.setGravity = function (gravity) {
  75710. this.gravity = gravity;
  75711. this._physicsPlugin.setGravity(this.gravity);
  75712. };
  75713. /**
  75714. * Set the time step of the physics engine.
  75715. * default is 1/60.
  75716. * To slow it down, enter 1/600 for example.
  75717. * To speed it up, 1/30
  75718. * @param {number} newTimeStep the new timestep to apply to this world.
  75719. */
  75720. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  75721. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  75722. this._physicsPlugin.setTimeStep(newTimeStep);
  75723. };
  75724. /**
  75725. * Get the time step of the physics engine.
  75726. */
  75727. PhysicsEngine.prototype.getTimeStep = function () {
  75728. return this._physicsPlugin.getTimeStep();
  75729. };
  75730. PhysicsEngine.prototype.dispose = function () {
  75731. this._impostors.forEach(function (impostor) {
  75732. impostor.dispose();
  75733. });
  75734. this._physicsPlugin.dispose();
  75735. };
  75736. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  75737. return this._physicsPlugin.name;
  75738. };
  75739. /**
  75740. * Adding a new impostor for the impostor tracking.
  75741. * This will be done by the impostor itself.
  75742. * @param {PhysicsImpostor} impostor the impostor to add
  75743. */
  75744. PhysicsEngine.prototype.addImpostor = function (impostor) {
  75745. impostor.uniqueId = this._impostors.push(impostor);
  75746. //if no parent, generate the body
  75747. if (!impostor.parent) {
  75748. this._physicsPlugin.generatePhysicsBody(impostor);
  75749. }
  75750. };
  75751. /**
  75752. * Remove an impostor from the engine.
  75753. * This impostor and its mesh will not longer be updated by the physics engine.
  75754. * @param {PhysicsImpostor} impostor the impostor to remove
  75755. */
  75756. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  75757. var index = this._impostors.indexOf(impostor);
  75758. if (index > -1) {
  75759. var removed = this._impostors.splice(index, 1);
  75760. //Is it needed?
  75761. if (removed.length) {
  75762. //this will also remove it from the world.
  75763. removed[0].physicsBody = null;
  75764. }
  75765. }
  75766. };
  75767. /**
  75768. * Add a joint to the physics engine
  75769. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  75770. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  75771. * @param {PhysicsJoint} the joint that will connect both impostors.
  75772. */
  75773. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  75774. var impostorJoint = {
  75775. mainImpostor: mainImpostor,
  75776. connectedImpostor: connectedImpostor,
  75777. joint: joint
  75778. };
  75779. joint.physicsPlugin = this._physicsPlugin;
  75780. this._joints.push(impostorJoint);
  75781. this._physicsPlugin.generateJoint(impostorJoint);
  75782. };
  75783. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  75784. var matchingJoints = this._joints.filter(function (impostorJoint) {
  75785. return (impostorJoint.connectedImpostor === connectedImpostor
  75786. && impostorJoint.joint === joint
  75787. && impostorJoint.mainImpostor === mainImpostor);
  75788. });
  75789. if (matchingJoints.length) {
  75790. this._physicsPlugin.removeJoint(matchingJoints[0]);
  75791. //TODO remove it from the list as well
  75792. }
  75793. };
  75794. /**
  75795. * Called by the scene. no need to call it.
  75796. */
  75797. PhysicsEngine.prototype._step = function (delta) {
  75798. var _this = this;
  75799. //check if any mesh has no body / requires an update
  75800. this._impostors.forEach(function (impostor) {
  75801. if (impostor.isBodyInitRequired()) {
  75802. _this._physicsPlugin.generatePhysicsBody(impostor);
  75803. }
  75804. });
  75805. if (delta > 0.1) {
  75806. delta = 0.1;
  75807. }
  75808. else if (delta <= 0) {
  75809. delta = 1.0 / 60.0;
  75810. }
  75811. this._physicsPlugin.executeStep(delta, this._impostors);
  75812. };
  75813. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  75814. return this._physicsPlugin;
  75815. };
  75816. PhysicsEngine.prototype.getImpostors = function () {
  75817. return this._impostors;
  75818. };
  75819. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  75820. for (var i = 0; i < this._impostors.length; ++i) {
  75821. if (this._impostors[i].object === object) {
  75822. return this._impostors[i];
  75823. }
  75824. }
  75825. return null;
  75826. };
  75827. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  75828. for (var i = 0; i < this._impostors.length; ++i) {
  75829. if (this._impostors[i].physicsBody === body) {
  75830. return this._impostors[i];
  75831. }
  75832. }
  75833. return null;
  75834. };
  75835. // Statics
  75836. PhysicsEngine.Epsilon = 0.001;
  75837. return PhysicsEngine;
  75838. }());
  75839. BABYLON.PhysicsEngine = PhysicsEngine;
  75840. })(BABYLON || (BABYLON = {}));
  75841. //# sourceMappingURL=babylon.physicsEngine.js.map
  75842. var BABYLON;
  75843. (function (BABYLON) {
  75844. var PhysicsHelper = /** @class */ (function () {
  75845. function PhysicsHelper(scene) {
  75846. this._scene = scene;
  75847. this._physicsEngine = this._scene.getPhysicsEngine();
  75848. if (!this._physicsEngine) {
  75849. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  75850. }
  75851. }
  75852. /**
  75853. * @param {Vector3} origin the origin of the explosion
  75854. * @param {number} radius the explosion radius
  75855. * @param {number} strength the explosion strength
  75856. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  75857. */
  75858. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  75859. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75860. if (!this._physicsEngine) {
  75861. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  75862. return null;
  75863. }
  75864. var impostors = this._physicsEngine.getImpostors();
  75865. if (impostors.length === 0) {
  75866. return null;
  75867. }
  75868. var event = new PhysicsRadialExplosionEvent(this._scene);
  75869. impostors.forEach(function (impostor) {
  75870. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  75871. if (!impostorForceAndContactPoint) {
  75872. return;
  75873. }
  75874. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75875. });
  75876. event.dispose(false);
  75877. return event;
  75878. };
  75879. /**
  75880. * @param {Vector3} origin the origin of the explosion
  75881. * @param {number} radius the explosion radius
  75882. * @param {number} strength the explosion strength
  75883. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  75884. */
  75885. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  75886. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75887. if (!this._physicsEngine) {
  75888. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75889. return null;
  75890. }
  75891. var impostors = this._physicsEngine.getImpostors();
  75892. if (impostors.length === 0) {
  75893. return null;
  75894. }
  75895. var event = new PhysicsRadialExplosionEvent(this._scene);
  75896. impostors.forEach(function (impostor) {
  75897. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  75898. if (!impostorForceAndContactPoint) {
  75899. return;
  75900. }
  75901. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75902. });
  75903. event.dispose(false);
  75904. return event;
  75905. };
  75906. /**
  75907. * @param {Vector3} origin the origin of the explosion
  75908. * @param {number} radius the explosion radius
  75909. * @param {number} strength the explosion strength
  75910. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  75911. */
  75912. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  75913. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75914. if (!this._physicsEngine) {
  75915. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75916. return null;
  75917. }
  75918. var impostors = this._physicsEngine.getImpostors();
  75919. if (impostors.length === 0) {
  75920. return null;
  75921. }
  75922. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  75923. event.dispose(false);
  75924. return event;
  75925. };
  75926. /**
  75927. * @param {Vector3} origin the origin of the updraft
  75928. * @param {number} radius the radius of the updraft
  75929. * @param {number} strength the strength of the updraft
  75930. * @param {number} height the height of the updraft
  75931. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  75932. */
  75933. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  75934. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  75935. if (!this._physicsEngine) {
  75936. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75937. return null;
  75938. }
  75939. if (this._physicsEngine.getImpostors().length === 0) {
  75940. return null;
  75941. }
  75942. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  75943. event.dispose(false);
  75944. return event;
  75945. };
  75946. /**
  75947. * @param {Vector3} origin the of the vortex
  75948. * @param {number} radius the radius of the vortex
  75949. * @param {number} strength the strength of the vortex
  75950. * @param {number} height the height of the vortex
  75951. */
  75952. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  75953. if (!this._physicsEngine) {
  75954. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75955. return null;
  75956. }
  75957. if (this._physicsEngine.getImpostors().length === 0) {
  75958. return null;
  75959. }
  75960. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  75961. event.dispose(false);
  75962. return event;
  75963. };
  75964. return PhysicsHelper;
  75965. }());
  75966. BABYLON.PhysicsHelper = PhysicsHelper;
  75967. /***** Radial explosion *****/
  75968. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  75969. function PhysicsRadialExplosionEvent(scene) {
  75970. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  75971. this._rays = [];
  75972. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  75973. this._scene = scene;
  75974. }
  75975. /**
  75976. * Returns the data related to the radial explosion event (sphere & rays).
  75977. * @returns {PhysicsRadialExplosionEventData}
  75978. */
  75979. PhysicsRadialExplosionEvent.prototype.getData = function () {
  75980. this._dataFetched = true;
  75981. return {
  75982. sphere: this._sphere,
  75983. rays: this._rays,
  75984. };
  75985. };
  75986. /**
  75987. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  75988. * @param impostor
  75989. * @param {Vector3} origin the origin of the explosion
  75990. * @param {number} radius the explosion radius
  75991. * @param {number} strength the explosion strength
  75992. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  75993. * @returns {Nullable<PhysicsForceAndContactPoint>}
  75994. */
  75995. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  75996. if (impostor.mass === 0) {
  75997. return null;
  75998. }
  75999. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  76000. return null;
  76001. }
  76002. if (impostor.object.getClassName() !== 'Mesh') {
  76003. return null;
  76004. }
  76005. var impostorObject = impostor.object;
  76006. var impostorObjectCenter = impostor.getObjectCenter();
  76007. var direction = impostorObjectCenter.subtract(origin);
  76008. var ray = new BABYLON.Ray(origin, direction, radius);
  76009. this._rays.push(ray);
  76010. var hit = ray.intersectsMesh(impostorObject);
  76011. var contactPoint = hit.pickedPoint;
  76012. if (!contactPoint) {
  76013. return null;
  76014. }
  76015. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  76016. if (distanceFromOrigin > radius) {
  76017. return null;
  76018. }
  76019. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  76020. ? strength
  76021. : strength * (1 - (distanceFromOrigin / radius));
  76022. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  76023. return { force: force, contactPoint: contactPoint };
  76024. };
  76025. /**
  76026. * Disposes the sphere.
  76027. * @param {bolean} force
  76028. */
  76029. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  76030. var _this = this;
  76031. if (force === void 0) { force = true; }
  76032. if (force) {
  76033. this._sphere.dispose();
  76034. }
  76035. else {
  76036. setTimeout(function () {
  76037. if (!_this._dataFetched) {
  76038. _this._sphere.dispose();
  76039. }
  76040. }, 0);
  76041. }
  76042. };
  76043. /*** Helpers ***/
  76044. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  76045. if (!this._sphere) {
  76046. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  76047. this._sphere.isVisible = false;
  76048. }
  76049. };
  76050. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  76051. var impostorObject = impostor.object;
  76052. this._prepareSphere();
  76053. this._sphere.position = origin;
  76054. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  76055. this._sphere._updateBoundingInfo();
  76056. this._sphere.computeWorldMatrix(true);
  76057. return this._sphere.intersectsMesh(impostorObject, true);
  76058. };
  76059. return PhysicsRadialExplosionEvent;
  76060. }());
  76061. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  76062. /***** Gravitational Field *****/
  76063. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  76064. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  76065. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76066. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  76067. this._physicsHelper = physicsHelper;
  76068. this._scene = scene;
  76069. this._origin = origin;
  76070. this._radius = radius;
  76071. this._strength = strength;
  76072. this._falloff = falloff;
  76073. this._tickCallback = this._tick.bind(this);
  76074. }
  76075. /**
  76076. * Returns the data related to the gravitational field event (sphere).
  76077. * @returns {PhysicsGravitationalFieldEventData}
  76078. */
  76079. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  76080. this._dataFetched = true;
  76081. return {
  76082. sphere: this._sphere,
  76083. };
  76084. };
  76085. /**
  76086. * Enables the gravitational field.
  76087. */
  76088. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  76089. this._tickCallback.call(this);
  76090. this._scene.registerBeforeRender(this._tickCallback);
  76091. };
  76092. /**
  76093. * Disables the gravitational field.
  76094. */
  76095. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  76096. this._scene.unregisterBeforeRender(this._tickCallback);
  76097. };
  76098. /**
  76099. * Disposes the sphere.
  76100. * @param {bolean} force
  76101. */
  76102. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  76103. var _this = this;
  76104. if (force === void 0) { force = true; }
  76105. if (force) {
  76106. this._sphere.dispose();
  76107. }
  76108. else {
  76109. setTimeout(function () {
  76110. if (!_this._dataFetched) {
  76111. _this._sphere.dispose();
  76112. }
  76113. }, 0);
  76114. }
  76115. };
  76116. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  76117. // Since the params won't change, we fetch the event only once
  76118. if (this._sphere) {
  76119. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  76120. }
  76121. else {
  76122. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  76123. if (radialExplosionEvent) {
  76124. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  76125. }
  76126. }
  76127. };
  76128. return PhysicsGravitationalFieldEvent;
  76129. }());
  76130. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  76131. /***** Updraft *****/
  76132. var PhysicsUpdraftEvent = /** @class */ (function () {
  76133. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  76134. this._scene = _scene;
  76135. this._origin = _origin;
  76136. this._radius = _radius;
  76137. this._strength = _strength;
  76138. this._height = _height;
  76139. this._updraftMode = _updraftMode;
  76140. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  76141. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  76142. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  76143. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  76144. this._physicsEngine = this._scene.getPhysicsEngine();
  76145. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  76146. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  76147. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  76148. this._originDirection = this._origin.subtract(this._originTop).normalize();
  76149. }
  76150. this._tickCallback = this._tick.bind(this);
  76151. }
  76152. /**
  76153. * Returns the data related to the updraft event (cylinder).
  76154. * @returns {PhysicsUpdraftEventData}
  76155. */
  76156. PhysicsUpdraftEvent.prototype.getData = function () {
  76157. this._dataFetched = true;
  76158. return {
  76159. cylinder: this._cylinder,
  76160. };
  76161. };
  76162. /**
  76163. * Enables the updraft.
  76164. */
  76165. PhysicsUpdraftEvent.prototype.enable = function () {
  76166. this._tickCallback.call(this);
  76167. this._scene.registerBeforeRender(this._tickCallback);
  76168. };
  76169. /**
  76170. * Disables the cortex.
  76171. */
  76172. PhysicsUpdraftEvent.prototype.disable = function () {
  76173. this._scene.unregisterBeforeRender(this._tickCallback);
  76174. };
  76175. /**
  76176. * Disposes the sphere.
  76177. * @param {bolean} force
  76178. */
  76179. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  76180. var _this = this;
  76181. if (force === void 0) { force = true; }
  76182. if (force) {
  76183. this._cylinder.dispose();
  76184. }
  76185. else {
  76186. setTimeout(function () {
  76187. if (!_this._dataFetched) {
  76188. _this._cylinder.dispose();
  76189. }
  76190. }, 0);
  76191. }
  76192. };
  76193. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  76194. if (impostor.mass === 0) {
  76195. return null;
  76196. }
  76197. if (!this._intersectsWithCylinder(impostor)) {
  76198. return null;
  76199. }
  76200. var impostorObjectCenter = impostor.getObjectCenter();
  76201. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  76202. var direction = this._originDirection;
  76203. }
  76204. else {
  76205. var direction = impostorObjectCenter.subtract(this._originTop);
  76206. }
  76207. var multiplier = this._strength * -1;
  76208. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  76209. return { force: force, contactPoint: impostorObjectCenter };
  76210. };
  76211. PhysicsUpdraftEvent.prototype._tick = function () {
  76212. var _this = this;
  76213. this._physicsEngine.getImpostors().forEach(function (impostor) {
  76214. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  76215. if (!impostorForceAndContactPoint) {
  76216. return;
  76217. }
  76218. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76219. });
  76220. };
  76221. /*** Helpers ***/
  76222. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  76223. if (!this._cylinder) {
  76224. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  76225. height: this._height,
  76226. diameter: this._radius * 2,
  76227. }, this._scene);
  76228. this._cylinder.isVisible = false;
  76229. }
  76230. };
  76231. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  76232. var impostorObject = impostor.object;
  76233. this._prepareCylinder();
  76234. this._cylinder.position = this._cylinderPosition;
  76235. return this._cylinder.intersectsMesh(impostorObject, true);
  76236. };
  76237. return PhysicsUpdraftEvent;
  76238. }());
  76239. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  76240. /***** Vortex *****/
  76241. var PhysicsVortexEvent = /** @class */ (function () {
  76242. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  76243. this._scene = _scene;
  76244. this._origin = _origin;
  76245. this._radius = _radius;
  76246. this._strength = _strength;
  76247. this._height = _height;
  76248. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  76249. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  76250. this._updraftMultiplier = 0.02;
  76251. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  76252. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  76253. this._physicsEngine = this._scene.getPhysicsEngine();
  76254. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  76255. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  76256. this._tickCallback = this._tick.bind(this);
  76257. }
  76258. /**
  76259. * Returns the data related to the vortex event (cylinder).
  76260. * @returns {PhysicsVortexEventData}
  76261. */
  76262. PhysicsVortexEvent.prototype.getData = function () {
  76263. this._dataFetched = true;
  76264. return {
  76265. cylinder: this._cylinder,
  76266. };
  76267. };
  76268. /**
  76269. * Enables the vortex.
  76270. */
  76271. PhysicsVortexEvent.prototype.enable = function () {
  76272. this._tickCallback.call(this);
  76273. this._scene.registerBeforeRender(this._tickCallback);
  76274. };
  76275. /**
  76276. * Disables the cortex.
  76277. */
  76278. PhysicsVortexEvent.prototype.disable = function () {
  76279. this._scene.unregisterBeforeRender(this._tickCallback);
  76280. };
  76281. /**
  76282. * Disposes the sphere.
  76283. * @param {bolean} force
  76284. */
  76285. PhysicsVortexEvent.prototype.dispose = function (force) {
  76286. var _this = this;
  76287. if (force === void 0) { force = true; }
  76288. if (force) {
  76289. this._cylinder.dispose();
  76290. }
  76291. else {
  76292. setTimeout(function () {
  76293. if (!_this._dataFetched) {
  76294. _this._cylinder.dispose();
  76295. }
  76296. }, 0);
  76297. }
  76298. };
  76299. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  76300. if (impostor.mass === 0) {
  76301. return null;
  76302. }
  76303. if (!this._intersectsWithCylinder(impostor)) {
  76304. return null;
  76305. }
  76306. if (impostor.object.getClassName() !== 'Mesh') {
  76307. return null;
  76308. }
  76309. var impostorObject = impostor.object;
  76310. var impostorObjectCenter = impostor.getObjectCenter();
  76311. 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)
  76312. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  76313. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  76314. var hit = ray.intersectsMesh(impostorObject);
  76315. var contactPoint = hit.pickedPoint;
  76316. if (!contactPoint) {
  76317. return null;
  76318. }
  76319. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  76320. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  76321. var directionToOrigin = contactPoint.normalize();
  76322. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  76323. directionToOrigin = directionToOrigin.negate();
  76324. }
  76325. // TODO: find a more physically based solution
  76326. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  76327. var forceX = directionToOrigin.x * this._strength / 8;
  76328. var forceY = directionToOrigin.y * this._updraftMultiplier;
  76329. var forceZ = directionToOrigin.z * this._strength / 8;
  76330. }
  76331. else {
  76332. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  76333. var forceY = this._originTop.y * this._updraftMultiplier;
  76334. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  76335. }
  76336. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  76337. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  76338. return { force: force, contactPoint: impostorObjectCenter };
  76339. };
  76340. PhysicsVortexEvent.prototype._tick = function () {
  76341. var _this = this;
  76342. this._physicsEngine.getImpostors().forEach(function (impostor) {
  76343. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  76344. if (!impostorForceAndContactPoint) {
  76345. return;
  76346. }
  76347. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76348. });
  76349. };
  76350. /*** Helpers ***/
  76351. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  76352. if (!this._cylinder) {
  76353. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  76354. height: this._height,
  76355. diameter: this._radius * 2,
  76356. }, this._scene);
  76357. this._cylinder.isVisible = false;
  76358. }
  76359. };
  76360. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  76361. var impostorObject = impostor.object;
  76362. this._prepareCylinder();
  76363. this._cylinder.position = this._cylinderPosition;
  76364. return this._cylinder.intersectsMesh(impostorObject, true);
  76365. };
  76366. return PhysicsVortexEvent;
  76367. }());
  76368. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  76369. /***** Enums *****/
  76370. /**
  76371. * The strenght of the force in correspondence to the distance of the affected object
  76372. */
  76373. var PhysicsRadialImpulseFalloff;
  76374. (function (PhysicsRadialImpulseFalloff) {
  76375. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  76376. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  76377. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  76378. /**
  76379. * The strenght of the force in correspondence to the distance of the affected object
  76380. */
  76381. var PhysicsUpdraftMode;
  76382. (function (PhysicsUpdraftMode) {
  76383. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  76384. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  76385. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  76386. })(BABYLON || (BABYLON = {}));
  76387. //# sourceMappingURL=babylon.physicsHelper.js.map
  76388. var BABYLON;
  76389. (function (BABYLON) {
  76390. var CannonJSPlugin = /** @class */ (function () {
  76391. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  76392. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  76393. if (iterations === void 0) { iterations = 10; }
  76394. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  76395. this.name = "CannonJSPlugin";
  76396. this._physicsMaterials = new Array();
  76397. this._fixedTimeStep = 1 / 60;
  76398. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  76399. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : ( true ? __webpack_require__(17) : undefined);
  76400. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  76401. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  76402. this._tmpPosition = BABYLON.Vector3.Zero();
  76403. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  76404. this._tmpUnityRotation = new BABYLON.Quaternion();
  76405. if (!this.isSupported()) {
  76406. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  76407. return;
  76408. }
  76409. this._extendNamespace();
  76410. this.world = new this.BJSCANNON.World();
  76411. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  76412. this.world.solver.iterations = iterations;
  76413. }
  76414. CannonJSPlugin.prototype.setGravity = function (gravity) {
  76415. this.world.gravity.copy(gravity);
  76416. };
  76417. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  76418. this._fixedTimeStep = timeStep;
  76419. };
  76420. CannonJSPlugin.prototype.getTimeStep = function () {
  76421. return this._fixedTimeStep;
  76422. };
  76423. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  76424. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  76425. };
  76426. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  76427. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  76428. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  76429. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  76430. };
  76431. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  76432. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  76433. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  76434. impostor.physicsBody.applyForce(impulse, worldPoint);
  76435. };
  76436. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  76437. //parent-child relationship. Does this impostor has a parent impostor?
  76438. if (impostor.parent) {
  76439. if (impostor.physicsBody) {
  76440. this.removePhysicsBody(impostor);
  76441. //TODO is that needed?
  76442. impostor.forceUpdate();
  76443. }
  76444. return;
  76445. }
  76446. //should a new body be created for this impostor?
  76447. if (impostor.isBodyInitRequired()) {
  76448. var shape = this._createShape(impostor);
  76449. //unregister events, if body is being changed
  76450. var oldBody = impostor.physicsBody;
  76451. if (oldBody) {
  76452. this.removePhysicsBody(impostor);
  76453. }
  76454. //create the body and material
  76455. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  76456. var bodyCreationObject = {
  76457. mass: impostor.getParam("mass"),
  76458. material: material
  76459. };
  76460. // A simple extend, in case native options were used.
  76461. var nativeOptions = impostor.getParam("nativeOptions");
  76462. for (var key in nativeOptions) {
  76463. if (nativeOptions.hasOwnProperty(key)) {
  76464. bodyCreationObject[key] = nativeOptions[key];
  76465. }
  76466. }
  76467. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  76468. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  76469. this.world.addEventListener("preStep", impostor.beforeStep);
  76470. this.world.addEventListener("postStep", impostor.afterStep);
  76471. impostor.physicsBody.addShape(shape);
  76472. this.world.add(impostor.physicsBody);
  76473. //try to keep the body moving in the right direction by taking old properties.
  76474. //Should be tested!
  76475. if (oldBody) {
  76476. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  76477. impostor.physicsBody[param].copy(oldBody[param]);
  76478. });
  76479. }
  76480. this._processChildMeshes(impostor);
  76481. }
  76482. //now update the body's transformation
  76483. this._updatePhysicsBodyTransformation(impostor);
  76484. };
  76485. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  76486. var _this = this;
  76487. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  76488. var currentRotation = mainImpostor.object.rotationQuaternion;
  76489. if (meshChildren.length) {
  76490. var processMesh = function (localPosition, mesh) {
  76491. if (!currentRotation || !mesh.rotationQuaternion) {
  76492. return;
  76493. }
  76494. var childImpostor = mesh.getPhysicsImpostor();
  76495. if (childImpostor) {
  76496. var parent = childImpostor.parent;
  76497. if (parent !== mainImpostor) {
  76498. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  76499. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  76500. if (childImpostor.physicsBody) {
  76501. _this.removePhysicsBody(childImpostor);
  76502. childImpostor.physicsBody = null;
  76503. }
  76504. childImpostor.parent = mainImpostor;
  76505. childImpostor.resetUpdateFlags();
  76506. 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));
  76507. //Add the mass of the children.
  76508. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  76509. }
  76510. }
  76511. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  76512. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  76513. };
  76514. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  76515. }
  76516. };
  76517. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  76518. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  76519. this.world.removeEventListener("preStep", impostor.beforeStep);
  76520. this.world.removeEventListener("postStep", impostor.afterStep);
  76521. this.world.remove(impostor.physicsBody);
  76522. };
  76523. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  76524. var mainBody = impostorJoint.mainImpostor.physicsBody;
  76525. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  76526. if (!mainBody || !connectedBody) {
  76527. return;
  76528. }
  76529. var constraint;
  76530. var jointData = impostorJoint.joint.jointData;
  76531. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  76532. var constraintData = {
  76533. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  76534. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  76535. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  76536. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  76537. maxForce: jointData.nativeParams.maxForce,
  76538. collideConnected: !!jointData.collision
  76539. };
  76540. switch (impostorJoint.joint.type) {
  76541. case BABYLON.PhysicsJoint.HingeJoint:
  76542. case BABYLON.PhysicsJoint.Hinge2Joint:
  76543. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  76544. break;
  76545. case BABYLON.PhysicsJoint.DistanceJoint:
  76546. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  76547. break;
  76548. case BABYLON.PhysicsJoint.SpringJoint:
  76549. var springData = jointData;
  76550. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  76551. restLength: springData.length,
  76552. stiffness: springData.stiffness,
  76553. damping: springData.damping,
  76554. localAnchorA: constraintData.pivotA,
  76555. localAnchorB: constraintData.pivotB
  76556. });
  76557. break;
  76558. case BABYLON.PhysicsJoint.LockJoint:
  76559. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  76560. break;
  76561. case BABYLON.PhysicsJoint.PointToPointJoint:
  76562. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  76563. default:
  76564. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  76565. break;
  76566. }
  76567. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  76568. constraint.collideConnected = !!jointData.collision;
  76569. impostorJoint.joint.physicsJoint = constraint;
  76570. //don't add spring as constraint, as it is not one.
  76571. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  76572. this.world.addConstraint(constraint);
  76573. }
  76574. else {
  76575. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  76576. constraint.applyForce();
  76577. });
  76578. }
  76579. };
  76580. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  76581. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  76582. };
  76583. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  76584. var index;
  76585. var mat;
  76586. for (index = 0; index < this._physicsMaterials.length; index++) {
  76587. mat = this._physicsMaterials[index];
  76588. if (mat.friction === friction && mat.restitution === restitution) {
  76589. return mat;
  76590. }
  76591. }
  76592. var currentMat = new this.BJSCANNON.Material(name);
  76593. currentMat.friction = friction;
  76594. currentMat.restitution = restitution;
  76595. this._physicsMaterials.push(currentMat);
  76596. return currentMat;
  76597. };
  76598. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  76599. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  76600. };
  76601. CannonJSPlugin.prototype._createShape = function (impostor) {
  76602. var object = impostor.object;
  76603. var returnValue;
  76604. var extendSize = impostor.getObjectExtendSize();
  76605. switch (impostor.type) {
  76606. case BABYLON.PhysicsImpostor.SphereImpostor:
  76607. var radiusX = extendSize.x;
  76608. var radiusY = extendSize.y;
  76609. var radiusZ = extendSize.z;
  76610. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  76611. break;
  76612. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  76613. case BABYLON.PhysicsImpostor.CylinderImpostor:
  76614. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  76615. break;
  76616. case BABYLON.PhysicsImpostor.BoxImpostor:
  76617. var box = extendSize.scale(0.5);
  76618. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  76619. break;
  76620. case BABYLON.PhysicsImpostor.PlaneImpostor:
  76621. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  76622. returnValue = new this.BJSCANNON.Plane();
  76623. break;
  76624. case BABYLON.PhysicsImpostor.MeshImpostor:
  76625. // should transform the vertex data to world coordinates!!
  76626. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  76627. var rawFaces = object.getIndices ? object.getIndices() : [];
  76628. if (!rawVerts)
  76629. return;
  76630. // get only scale! so the object could transform correctly.
  76631. var oldPosition = object.position.clone();
  76632. var oldRotation = object.rotation && object.rotation.clone();
  76633. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  76634. object.position.copyFromFloats(0, 0, 0);
  76635. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  76636. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  76637. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  76638. var transform = object.computeWorldMatrix(true);
  76639. // convert rawVerts to object space
  76640. var temp = new Array();
  76641. var index;
  76642. for (index = 0; index < rawVerts.length; index += 3) {
  76643. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  76644. }
  76645. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  76646. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  76647. //now set back the transformation!
  76648. object.position.copyFrom(oldPosition);
  76649. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  76650. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  76651. break;
  76652. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  76653. var oldPosition2 = object.position.clone();
  76654. var oldRotation2 = object.rotation && object.rotation.clone();
  76655. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  76656. object.position.copyFromFloats(0, 0, 0);
  76657. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  76658. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  76659. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  76660. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  76661. returnValue = this._createHeightmap(object);
  76662. object.position.copyFrom(oldPosition2);
  76663. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  76664. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  76665. object.computeWorldMatrix(true);
  76666. break;
  76667. case BABYLON.PhysicsImpostor.ParticleImpostor:
  76668. returnValue = new this.BJSCANNON.Particle();
  76669. break;
  76670. }
  76671. return returnValue;
  76672. };
  76673. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  76674. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  76675. var transform = object.computeWorldMatrix(true);
  76676. // convert rawVerts to object space
  76677. var temp = new Array();
  76678. var index;
  76679. for (index = 0; index < pos.length; index += 3) {
  76680. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  76681. }
  76682. pos = temp;
  76683. var matrix = new Array();
  76684. //For now pointDepth will not be used and will be automatically calculated.
  76685. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  76686. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  76687. var boundingInfo = object.getBoundingInfo();
  76688. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  76689. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  76690. var elementSize = dim * 2 / arraySize;
  76691. for (var i = 0; i < pos.length; i = i + 3) {
  76692. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  76693. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  76694. var y = -pos[i + 2] + minY;
  76695. if (!matrix[x]) {
  76696. matrix[x] = [];
  76697. }
  76698. if (!matrix[x][z]) {
  76699. matrix[x][z] = y;
  76700. }
  76701. matrix[x][z] = Math.max(y, matrix[x][z]);
  76702. }
  76703. for (var x = 0; x <= arraySize; ++x) {
  76704. if (!matrix[x]) {
  76705. var loc = 1;
  76706. while (!matrix[(x + loc) % arraySize]) {
  76707. loc++;
  76708. }
  76709. matrix[x] = matrix[(x + loc) % arraySize].slice();
  76710. //console.log("missing x", x);
  76711. }
  76712. for (var z = 0; z <= arraySize; ++z) {
  76713. if (!matrix[x][z]) {
  76714. var loc = 1;
  76715. var newValue;
  76716. while (newValue === undefined) {
  76717. newValue = matrix[x][(z + loc++) % arraySize];
  76718. }
  76719. matrix[x][z] = newValue;
  76720. }
  76721. }
  76722. }
  76723. var shape = new this.BJSCANNON.Heightfield(matrix, {
  76724. elementSize: elementSize
  76725. });
  76726. //For future reference, needed for body transformation
  76727. shape.minY = minY;
  76728. return shape;
  76729. };
  76730. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  76731. var object = impostor.object;
  76732. //make sure it is updated...
  76733. object.computeWorldMatrix && object.computeWorldMatrix(true);
  76734. // The delta between the mesh position and the mesh bounding box center
  76735. var bInfo = object.getBoundingInfo();
  76736. if (!bInfo)
  76737. return;
  76738. var center = impostor.getObjectCenter();
  76739. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  76740. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  76741. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  76742. this._tmpPosition.copyFrom(center);
  76743. var quaternion = object.rotationQuaternion;
  76744. if (!quaternion) {
  76745. return;
  76746. }
  76747. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  76748. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  76749. //-90 DEG in X, precalculated
  76750. quaternion = quaternion.multiply(this._minus90X);
  76751. //Invert! (Precalculated, 90 deg in X)
  76752. //No need to clone. this will never change.
  76753. impostor.setDeltaRotation(this._plus90X);
  76754. }
  76755. //If it is a heightfield, if should be centered.
  76756. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  76757. var mesh = object;
  76758. var boundingInfo = mesh.getBoundingInfo();
  76759. //calculate the correct body position:
  76760. var rotationQuaternion = mesh.rotationQuaternion;
  76761. mesh.rotationQuaternion = this._tmpUnityRotation;
  76762. mesh.computeWorldMatrix(true);
  76763. //get original center with no rotation
  76764. var c = center.clone();
  76765. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  76766. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  76767. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  76768. mesh.setPreTransformMatrix(p);
  76769. mesh.computeWorldMatrix(true);
  76770. //calculate the translation
  76771. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  76772. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  76773. //add it inverted to the delta
  76774. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  76775. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  76776. //rotation is back
  76777. mesh.rotationQuaternion = rotationQuaternion;
  76778. mesh.setPreTransformMatrix(oldPivot);
  76779. mesh.computeWorldMatrix(true);
  76780. }
  76781. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  76782. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  76783. //this._tmpPosition.copyFrom(object.position);
  76784. }
  76785. impostor.setDeltaPosition(this._tmpDeltaPosition);
  76786. //Now update the impostor object
  76787. impostor.physicsBody.position.copy(this._tmpPosition);
  76788. impostor.physicsBody.quaternion.copy(quaternion);
  76789. };
  76790. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  76791. impostor.object.position.copyFrom(impostor.physicsBody.position);
  76792. if (impostor.object.rotationQuaternion) {
  76793. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  76794. }
  76795. };
  76796. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  76797. impostor.physicsBody.position.copy(newPosition);
  76798. impostor.physicsBody.quaternion.copy(newRotation);
  76799. };
  76800. CannonJSPlugin.prototype.isSupported = function () {
  76801. return this.BJSCANNON !== undefined;
  76802. };
  76803. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  76804. impostor.physicsBody.velocity.copy(velocity);
  76805. };
  76806. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  76807. impostor.physicsBody.angularVelocity.copy(velocity);
  76808. };
  76809. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  76810. var v = impostor.physicsBody.velocity;
  76811. if (!v) {
  76812. return null;
  76813. }
  76814. return new BABYLON.Vector3(v.x, v.y, v.z);
  76815. };
  76816. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  76817. var v = impostor.physicsBody.angularVelocity;
  76818. if (!v) {
  76819. return null;
  76820. }
  76821. return new BABYLON.Vector3(v.x, v.y, v.z);
  76822. };
  76823. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  76824. impostor.physicsBody.mass = mass;
  76825. impostor.physicsBody.updateMassProperties();
  76826. };
  76827. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  76828. return impostor.physicsBody.mass;
  76829. };
  76830. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  76831. return impostor.physicsBody.material.friction;
  76832. };
  76833. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  76834. impostor.physicsBody.material.friction = friction;
  76835. };
  76836. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  76837. return impostor.physicsBody.material.restitution;
  76838. };
  76839. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  76840. impostor.physicsBody.material.restitution = restitution;
  76841. };
  76842. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  76843. impostor.physicsBody.sleep();
  76844. };
  76845. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  76846. impostor.physicsBody.wakeUp();
  76847. };
  76848. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  76849. joint.physicsJoint.distance = maxDistance;
  76850. };
  76851. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  76852. // if (!motorIndex) {
  76853. // joint.physicsJoint.enableMotor();
  76854. // }
  76855. // }
  76856. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  76857. // if (!motorIndex) {
  76858. // joint.physicsJoint.disableMotor();
  76859. // }
  76860. // }
  76861. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  76862. if (!motorIndex) {
  76863. joint.physicsJoint.enableMotor();
  76864. joint.physicsJoint.setMotorSpeed(speed);
  76865. if (maxForce) {
  76866. this.setLimit(joint, maxForce);
  76867. }
  76868. }
  76869. };
  76870. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  76871. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  76872. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  76873. };
  76874. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  76875. var body = impostor.physicsBody;
  76876. mesh.position.x = body.position.x;
  76877. mesh.position.y = body.position.y;
  76878. mesh.position.z = body.position.z;
  76879. if (mesh.rotationQuaternion) {
  76880. mesh.rotationQuaternion.x = body.quaternion.x;
  76881. mesh.rotationQuaternion.y = body.quaternion.y;
  76882. mesh.rotationQuaternion.z = body.quaternion.z;
  76883. mesh.rotationQuaternion.w = body.quaternion.w;
  76884. }
  76885. };
  76886. CannonJSPlugin.prototype.getRadius = function (impostor) {
  76887. var shape = impostor.physicsBody.shapes[0];
  76888. return shape.boundingSphereRadius;
  76889. };
  76890. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  76891. var shape = impostor.physicsBody.shapes[0];
  76892. result.x = shape.halfExtents.x * 2;
  76893. result.y = shape.halfExtents.y * 2;
  76894. result.z = shape.halfExtents.z * 2;
  76895. };
  76896. CannonJSPlugin.prototype.dispose = function () {
  76897. };
  76898. CannonJSPlugin.prototype._extendNamespace = function () {
  76899. //this will force cannon to execute at least one step when using interpolation
  76900. var step_tmp1 = new this.BJSCANNON.Vec3();
  76901. var Engine = this.BJSCANNON;
  76902. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  76903. maxSubSteps = maxSubSteps || 10;
  76904. timeSinceLastCalled = timeSinceLastCalled || 0;
  76905. if (timeSinceLastCalled === 0) {
  76906. this.internalStep(dt);
  76907. this.time += dt;
  76908. }
  76909. else {
  76910. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  76911. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  76912. var t0 = performance.now();
  76913. for (var i = 0; i !== internalSteps; i++) {
  76914. this.internalStep(dt);
  76915. if (performance.now() - t0 > dt * 1000) {
  76916. break;
  76917. }
  76918. }
  76919. this.time += timeSinceLastCalled;
  76920. var h = this.time % dt;
  76921. var h_div_dt = h / dt;
  76922. var interpvelo = step_tmp1;
  76923. var bodies = this.bodies;
  76924. for (var j = 0; j !== bodies.length; j++) {
  76925. var b = bodies[j];
  76926. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  76927. b.position.vsub(b.previousPosition, interpvelo);
  76928. interpvelo.scale(h_div_dt, interpvelo);
  76929. b.position.vadd(interpvelo, b.interpolatedPosition);
  76930. }
  76931. else {
  76932. b.interpolatedPosition.copy(b.position);
  76933. b.interpolatedQuaternion.copy(b.quaternion);
  76934. }
  76935. }
  76936. }
  76937. };
  76938. };
  76939. return CannonJSPlugin;
  76940. }());
  76941. BABYLON.CannonJSPlugin = CannonJSPlugin;
  76942. })(BABYLON || (BABYLON = {}));
  76943. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  76944. var BABYLON;
  76945. (function (BABYLON) {
  76946. var OimoJSPlugin = /** @class */ (function () {
  76947. function OimoJSPlugin(iterations) {
  76948. this.name = "OimoJSPlugin";
  76949. this._tmpImpostorsArray = [];
  76950. this._tmpPositionVector = BABYLON.Vector3.Zero();
  76951. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : ( true ? __webpack_require__(18) : undefined);
  76952. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  76953. this.world.worldscale(1);
  76954. this.world.clear();
  76955. //making sure no stats are calculated
  76956. this.world.isNoStat = true;
  76957. }
  76958. OimoJSPlugin.prototype.setGravity = function (gravity) {
  76959. this.world.gravity.copy(gravity);
  76960. };
  76961. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  76962. this.world.timeStep = timeStep;
  76963. };
  76964. OimoJSPlugin.prototype.getTimeStep = function () {
  76965. return this.world.timeStep;
  76966. };
  76967. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  76968. var _this = this;
  76969. impostors.forEach(function (impostor) {
  76970. impostor.beforeStep();
  76971. });
  76972. this.world.step();
  76973. impostors.forEach(function (impostor) {
  76974. impostor.afterStep();
  76975. //update the ordered impostors array
  76976. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  76977. });
  76978. //check for collisions
  76979. var contact = this.world.contacts;
  76980. while (contact !== null) {
  76981. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  76982. contact = contact.next;
  76983. continue;
  76984. }
  76985. //is this body colliding with any other? get the impostor
  76986. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  76987. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  76988. if (!mainImpostor || !collidingImpostor) {
  76989. contact = contact.next;
  76990. continue;
  76991. }
  76992. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  76993. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  76994. contact = contact.next;
  76995. }
  76996. };
  76997. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  76998. var mass = impostor.physicsBody.massInfo.mass;
  76999. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  77000. };
  77001. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  77002. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  77003. this.applyImpulse(impostor, force, contactPoint);
  77004. };
  77005. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  77006. var _this = this;
  77007. //parent-child relationship. Does this impostor has a parent impostor?
  77008. if (impostor.parent) {
  77009. if (impostor.physicsBody) {
  77010. this.removePhysicsBody(impostor);
  77011. //TODO is that needed?
  77012. impostor.forceUpdate();
  77013. }
  77014. return;
  77015. }
  77016. if (impostor.isBodyInitRequired()) {
  77017. var bodyConfig = {
  77018. name: impostor.uniqueId,
  77019. //Oimo must have mass, also for static objects.
  77020. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  77021. size: [],
  77022. type: [],
  77023. pos: [],
  77024. rot: [],
  77025. move: impostor.getParam("mass") !== 0,
  77026. //Supporting older versions of Oimo
  77027. world: this.world
  77028. };
  77029. var impostors = [impostor];
  77030. var addToArray = function (parent) {
  77031. if (!parent.getChildMeshes)
  77032. return;
  77033. parent.getChildMeshes().forEach(function (m) {
  77034. if (m.physicsImpostor) {
  77035. impostors.push(m.physicsImpostor);
  77036. //m.physicsImpostor._init();
  77037. }
  77038. });
  77039. };
  77040. addToArray(impostor.object);
  77041. var checkWithEpsilon_1 = function (value) {
  77042. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  77043. };
  77044. impostors.forEach(function (i) {
  77045. if (!impostor.object.rotationQuaternion) {
  77046. return;
  77047. }
  77048. //get the correct bounding box
  77049. var oldQuaternion = i.object.rotationQuaternion;
  77050. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  77051. x: impostor.object.rotationQuaternion.x,
  77052. y: impostor.object.rotationQuaternion.y,
  77053. z: impostor.object.rotationQuaternion.z,
  77054. s: impostor.object.rotationQuaternion.w
  77055. });
  77056. var extendSize = i.getObjectExtendSize();
  77057. if (i === impostor) {
  77058. var center = impostor.getObjectCenter();
  77059. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  77060. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  77061. //Can also use Array.prototype.push.apply
  77062. bodyConfig.pos.push(center.x);
  77063. bodyConfig.pos.push(center.y);
  77064. bodyConfig.pos.push(center.z);
  77065. //tmp solution
  77066. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  77067. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  77068. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  77069. }
  77070. else {
  77071. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  77072. bodyConfig.pos.push(localPosition.x);
  77073. bodyConfig.pos.push(localPosition.y);
  77074. bodyConfig.pos.push(localPosition.z);
  77075. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  77076. bodyConfig.rot.push(0);
  77077. bodyConfig.rot.push(0);
  77078. bodyConfig.rot.push(0);
  77079. }
  77080. // register mesh
  77081. switch (i.type) {
  77082. case BABYLON.PhysicsImpostor.ParticleImpostor:
  77083. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  77084. case BABYLON.PhysicsImpostor.SphereImpostor:
  77085. var radiusX = extendSize.x;
  77086. var radiusY = extendSize.y;
  77087. var radiusZ = extendSize.z;
  77088. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  77089. bodyConfig.type.push('sphere');
  77090. //due to the way oimo works with compounds, add 3 times
  77091. bodyConfig.size.push(size);
  77092. bodyConfig.size.push(size);
  77093. bodyConfig.size.push(size);
  77094. break;
  77095. case BABYLON.PhysicsImpostor.CylinderImpostor:
  77096. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  77097. var sizeY = checkWithEpsilon_1(extendSize.y);
  77098. bodyConfig.type.push('cylinder');
  77099. bodyConfig.size.push(sizeX);
  77100. bodyConfig.size.push(sizeY);
  77101. //due to the way oimo works with compounds, add one more value.
  77102. bodyConfig.size.push(sizeY);
  77103. break;
  77104. case BABYLON.PhysicsImpostor.PlaneImpostor:
  77105. case BABYLON.PhysicsImpostor.BoxImpostor:
  77106. default:
  77107. var sizeX = checkWithEpsilon_1(extendSize.x);
  77108. var sizeY = checkWithEpsilon_1(extendSize.y);
  77109. var sizeZ = checkWithEpsilon_1(extendSize.z);
  77110. bodyConfig.type.push('box');
  77111. bodyConfig.size.push(sizeX);
  77112. bodyConfig.size.push(sizeY);
  77113. bodyConfig.size.push(sizeZ);
  77114. break;
  77115. }
  77116. //actually not needed, but hey...
  77117. i.object.rotationQuaternion = oldQuaternion;
  77118. });
  77119. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  77120. }
  77121. else {
  77122. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  77123. }
  77124. impostor.setDeltaPosition(this._tmpPositionVector);
  77125. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  77126. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  77127. };
  77128. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  77129. //impostor.physicsBody.dispose();
  77130. //Same as : (older oimo versions)
  77131. this.world.removeRigidBody(impostor.physicsBody);
  77132. };
  77133. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  77134. var mainBody = impostorJoint.mainImpostor.physicsBody;
  77135. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  77136. if (!mainBody || !connectedBody) {
  77137. return;
  77138. }
  77139. var jointData = impostorJoint.joint.jointData;
  77140. var options = jointData.nativeParams || {};
  77141. var type;
  77142. var nativeJointData = {
  77143. body1: mainBody,
  77144. body2: connectedBody,
  77145. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  77146. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  77147. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  77148. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  77149. min: options.min,
  77150. max: options.max,
  77151. collision: options.collision || jointData.collision,
  77152. spring: options.spring,
  77153. //supporting older version of Oimo
  77154. world: this.world
  77155. };
  77156. switch (impostorJoint.joint.type) {
  77157. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  77158. type = "jointBall";
  77159. break;
  77160. case BABYLON.PhysicsJoint.SpringJoint:
  77161. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  77162. var springData = jointData;
  77163. nativeJointData.min = springData.length || nativeJointData.min;
  77164. //Max should also be set, just make sure it is at least min
  77165. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  77166. case BABYLON.PhysicsJoint.DistanceJoint:
  77167. type = "jointDistance";
  77168. nativeJointData.max = jointData.maxDistance;
  77169. break;
  77170. case BABYLON.PhysicsJoint.PrismaticJoint:
  77171. type = "jointPrisme";
  77172. break;
  77173. case BABYLON.PhysicsJoint.SliderJoint:
  77174. type = "jointSlide";
  77175. break;
  77176. case BABYLON.PhysicsJoint.WheelJoint:
  77177. type = "jointWheel";
  77178. break;
  77179. case BABYLON.PhysicsJoint.HingeJoint:
  77180. default:
  77181. type = "jointHinge";
  77182. break;
  77183. }
  77184. nativeJointData.type = type;
  77185. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  77186. };
  77187. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  77188. //Bug in Oimo prevents us from disposing a joint in the playground
  77189. //joint.joint.physicsJoint.dispose();
  77190. //So we will bruteforce it!
  77191. try {
  77192. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  77193. }
  77194. catch (e) {
  77195. BABYLON.Tools.Warn(e);
  77196. }
  77197. };
  77198. OimoJSPlugin.prototype.isSupported = function () {
  77199. return this.BJSOIMO !== undefined;
  77200. };
  77201. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  77202. if (!impostor.physicsBody.sleeping) {
  77203. //TODO check that
  77204. if (impostor.physicsBody.shapes.next) {
  77205. var parentShape = this._getLastShape(impostor.physicsBody);
  77206. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  77207. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  77208. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  77209. }
  77210. else {
  77211. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  77212. }
  77213. if (impostor.object.rotationQuaternion) {
  77214. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  77215. impostor.object.rotationQuaternion.normalize();
  77216. }
  77217. }
  77218. };
  77219. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  77220. var body = impostor.physicsBody;
  77221. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  77222. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  77223. body.syncShapes();
  77224. body.awake();
  77225. };
  77226. OimoJSPlugin.prototype._getLastShape = function (body) {
  77227. var lastShape = body.shapes;
  77228. while (lastShape.next) {
  77229. lastShape = lastShape.next;
  77230. }
  77231. return lastShape;
  77232. };
  77233. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  77234. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  77235. };
  77236. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  77237. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  77238. };
  77239. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  77240. var v = impostor.physicsBody.linearVelocity;
  77241. if (!v) {
  77242. return null;
  77243. }
  77244. return new BABYLON.Vector3(v.x, v.y, v.z);
  77245. };
  77246. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  77247. var v = impostor.physicsBody.angularVelocity;
  77248. if (!v) {
  77249. return null;
  77250. }
  77251. return new BABYLON.Vector3(v.x, v.y, v.z);
  77252. };
  77253. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  77254. var staticBody = mass === 0;
  77255. //this will actually set the body's density and not its mass.
  77256. //But this is how oimo treats the mass variable.
  77257. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  77258. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  77259. };
  77260. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  77261. return impostor.physicsBody.shapes.density;
  77262. };
  77263. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  77264. return impostor.physicsBody.shapes.friction;
  77265. };
  77266. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  77267. impostor.physicsBody.shapes.friction = friction;
  77268. };
  77269. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  77270. return impostor.physicsBody.shapes.restitution;
  77271. };
  77272. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  77273. impostor.physicsBody.shapes.restitution = restitution;
  77274. };
  77275. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  77276. impostor.physicsBody.sleep();
  77277. };
  77278. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  77279. impostor.physicsBody.awake();
  77280. };
  77281. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  77282. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  77283. if (minDistance !== void 0) {
  77284. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  77285. }
  77286. };
  77287. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  77288. //TODO separate rotational and transational motors.
  77289. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  77290. if (motor) {
  77291. motor.setMotor(speed, maxForce);
  77292. }
  77293. };
  77294. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  77295. //TODO separate rotational and transational motors.
  77296. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  77297. if (motor) {
  77298. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  77299. }
  77300. };
  77301. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  77302. var body = impostor.physicsBody;
  77303. mesh.position.x = body.position.x;
  77304. mesh.position.y = body.position.y;
  77305. mesh.position.z = body.position.z;
  77306. if (mesh.rotationQuaternion) {
  77307. mesh.rotationQuaternion.x = body.orientation.x;
  77308. mesh.rotationQuaternion.y = body.orientation.y;
  77309. mesh.rotationQuaternion.z = body.orientation.z;
  77310. mesh.rotationQuaternion.w = body.orientation.s;
  77311. }
  77312. };
  77313. OimoJSPlugin.prototype.getRadius = function (impostor) {
  77314. return impostor.physicsBody.shapes.radius;
  77315. };
  77316. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  77317. var shape = impostor.physicsBody.shapes;
  77318. result.x = shape.halfWidth * 2;
  77319. result.y = shape.halfHeight * 2;
  77320. result.z = shape.halfDepth * 2;
  77321. };
  77322. OimoJSPlugin.prototype.dispose = function () {
  77323. this.world.clear();
  77324. };
  77325. return OimoJSPlugin;
  77326. }());
  77327. BABYLON.OimoJSPlugin = OimoJSPlugin;
  77328. })(BABYLON || (BABYLON = {}));
  77329. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  77330. var BABYLON;
  77331. (function (BABYLON) {
  77332. /*
  77333. * Based on jsTGALoader - Javascript loader for TGA file
  77334. * By Vincent Thibault
  77335. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  77336. */
  77337. var TGATools = /** @class */ (function () {
  77338. function TGATools() {
  77339. }
  77340. TGATools.GetTGAHeader = function (data) {
  77341. var offset = 0;
  77342. var header = {
  77343. id_length: data[offset++],
  77344. colormap_type: data[offset++],
  77345. image_type: data[offset++],
  77346. colormap_index: data[offset++] | data[offset++] << 8,
  77347. colormap_length: data[offset++] | data[offset++] << 8,
  77348. colormap_size: data[offset++],
  77349. origin: [
  77350. data[offset++] | data[offset++] << 8,
  77351. data[offset++] | data[offset++] << 8
  77352. ],
  77353. width: data[offset++] | data[offset++] << 8,
  77354. height: data[offset++] | data[offset++] << 8,
  77355. pixel_size: data[offset++],
  77356. flags: data[offset++]
  77357. };
  77358. return header;
  77359. };
  77360. TGATools.UploadContent = function (gl, data) {
  77361. // Not enough data to contain header ?
  77362. if (data.length < 19) {
  77363. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  77364. return;
  77365. }
  77366. // Read Header
  77367. var offset = 18;
  77368. var header = TGATools.GetTGAHeader(data);
  77369. // Assume it's a valid Targa file.
  77370. if (header.id_length + offset > data.length) {
  77371. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  77372. return;
  77373. }
  77374. // Skip not needed data
  77375. offset += header.id_length;
  77376. var use_rle = false;
  77377. var use_pal = false;
  77378. var use_grey = false;
  77379. // Get some informations.
  77380. switch (header.image_type) {
  77381. case TGATools._TYPE_RLE_INDEXED:
  77382. use_rle = true;
  77383. case TGATools._TYPE_INDEXED:
  77384. use_pal = true;
  77385. break;
  77386. case TGATools._TYPE_RLE_RGB:
  77387. use_rle = true;
  77388. case TGATools._TYPE_RGB:
  77389. // use_rgb = true;
  77390. break;
  77391. case TGATools._TYPE_RLE_GREY:
  77392. use_rle = true;
  77393. case TGATools._TYPE_GREY:
  77394. use_grey = true;
  77395. break;
  77396. }
  77397. var pixel_data;
  77398. // var numAlphaBits = header.flags & 0xf;
  77399. var pixel_size = header.pixel_size >> 3;
  77400. var pixel_total = header.width * header.height * pixel_size;
  77401. // Read palettes
  77402. var palettes;
  77403. if (use_pal) {
  77404. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  77405. }
  77406. // Read LRE
  77407. if (use_rle) {
  77408. pixel_data = new Uint8Array(pixel_total);
  77409. var c, count, i;
  77410. var localOffset = 0;
  77411. var pixels = new Uint8Array(pixel_size);
  77412. while (offset < pixel_total && localOffset < pixel_total) {
  77413. c = data[offset++];
  77414. count = (c & 0x7f) + 1;
  77415. // RLE pixels
  77416. if (c & 0x80) {
  77417. // Bind pixel tmp array
  77418. for (i = 0; i < pixel_size; ++i) {
  77419. pixels[i] = data[offset++];
  77420. }
  77421. // Copy pixel array
  77422. for (i = 0; i < count; ++i) {
  77423. pixel_data.set(pixels, localOffset + i * pixel_size);
  77424. }
  77425. localOffset += pixel_size * count;
  77426. }
  77427. else {
  77428. count *= pixel_size;
  77429. for (i = 0; i < count; ++i) {
  77430. pixel_data[localOffset + i] = data[offset++];
  77431. }
  77432. localOffset += count;
  77433. }
  77434. }
  77435. }
  77436. else {
  77437. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  77438. }
  77439. // Load to texture
  77440. var x_start, y_start, x_step, y_step, y_end, x_end;
  77441. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  77442. default:
  77443. case TGATools._ORIGIN_UL:
  77444. x_start = 0;
  77445. x_step = 1;
  77446. x_end = header.width;
  77447. y_start = 0;
  77448. y_step = 1;
  77449. y_end = header.height;
  77450. break;
  77451. case TGATools._ORIGIN_BL:
  77452. x_start = 0;
  77453. x_step = 1;
  77454. x_end = header.width;
  77455. y_start = header.height - 1;
  77456. y_step = -1;
  77457. y_end = -1;
  77458. break;
  77459. case TGATools._ORIGIN_UR:
  77460. x_start = header.width - 1;
  77461. x_step = -1;
  77462. x_end = -1;
  77463. y_start = 0;
  77464. y_step = 1;
  77465. y_end = header.height;
  77466. break;
  77467. case TGATools._ORIGIN_BR:
  77468. x_start = header.width - 1;
  77469. x_step = -1;
  77470. x_end = -1;
  77471. y_start = header.height - 1;
  77472. y_step = -1;
  77473. y_end = -1;
  77474. break;
  77475. }
  77476. // Load the specify method
  77477. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  77478. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  77479. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  77480. };
  77481. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77482. var image = pixel_data, colormap = palettes;
  77483. var width = header.width, height = header.height;
  77484. var color, i = 0, x, y;
  77485. var imageData = new Uint8Array(width * height * 4);
  77486. for (y = y_start; y !== y_end; y += y_step) {
  77487. for (x = x_start; x !== x_end; x += x_step, i++) {
  77488. color = image[i];
  77489. imageData[(x + width * y) * 4 + 3] = 255;
  77490. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  77491. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  77492. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  77493. }
  77494. }
  77495. return imageData;
  77496. };
  77497. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77498. var image = pixel_data;
  77499. var width = header.width, height = header.height;
  77500. var color, i = 0, x, y;
  77501. var imageData = new Uint8Array(width * height * 4);
  77502. for (y = y_start; y !== y_end; y += y_step) {
  77503. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  77504. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  77505. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  77506. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  77507. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  77508. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  77509. }
  77510. }
  77511. return imageData;
  77512. };
  77513. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77514. var image = pixel_data;
  77515. var width = header.width, height = header.height;
  77516. var i = 0, x, y;
  77517. var imageData = new Uint8Array(width * height * 4);
  77518. for (y = y_start; y !== y_end; y += y_step) {
  77519. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  77520. imageData[(x + width * y) * 4 + 3] = 255;
  77521. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  77522. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  77523. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  77524. }
  77525. }
  77526. return imageData;
  77527. };
  77528. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77529. var image = pixel_data;
  77530. var width = header.width, height = header.height;
  77531. var i = 0, x, y;
  77532. var imageData = new Uint8Array(width * height * 4);
  77533. for (y = y_start; y !== y_end; y += y_step) {
  77534. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  77535. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  77536. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  77537. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  77538. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  77539. }
  77540. }
  77541. return imageData;
  77542. };
  77543. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77544. var image = pixel_data;
  77545. var width = header.width, height = header.height;
  77546. var color, i = 0, x, y;
  77547. var imageData = new Uint8Array(width * height * 4);
  77548. for (y = y_start; y !== y_end; y += y_step) {
  77549. for (x = x_start; x !== x_end; x += x_step, i++) {
  77550. color = image[i];
  77551. imageData[(x + width * y) * 4 + 0] = color;
  77552. imageData[(x + width * y) * 4 + 1] = color;
  77553. imageData[(x + width * y) * 4 + 2] = color;
  77554. imageData[(x + width * y) * 4 + 3] = 255;
  77555. }
  77556. }
  77557. return imageData;
  77558. };
  77559. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77560. var image = pixel_data;
  77561. var width = header.width, height = header.height;
  77562. var i = 0, x, y;
  77563. var imageData = new Uint8Array(width * height * 4);
  77564. for (y = y_start; y !== y_end; y += y_step) {
  77565. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  77566. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  77567. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  77568. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  77569. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  77570. }
  77571. }
  77572. return imageData;
  77573. };
  77574. //private static _TYPE_NO_DATA = 0;
  77575. TGATools._TYPE_INDEXED = 1;
  77576. TGATools._TYPE_RGB = 2;
  77577. TGATools._TYPE_GREY = 3;
  77578. TGATools._TYPE_RLE_INDEXED = 9;
  77579. TGATools._TYPE_RLE_RGB = 10;
  77580. TGATools._TYPE_RLE_GREY = 11;
  77581. TGATools._ORIGIN_MASK = 0x30;
  77582. TGATools._ORIGIN_SHIFT = 0x04;
  77583. TGATools._ORIGIN_BL = 0x00;
  77584. TGATools._ORIGIN_BR = 0x01;
  77585. TGATools._ORIGIN_UL = 0x02;
  77586. TGATools._ORIGIN_UR = 0x03;
  77587. return TGATools;
  77588. }());
  77589. BABYLON.TGATools = TGATools;
  77590. })(BABYLON || (BABYLON = {}));
  77591. //# sourceMappingURL=babylon.tga.js.map
  77592. var BABYLON;
  77593. (function (BABYLON) {
  77594. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  77595. // All values and structures referenced from:
  77596. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  77597. var DDS_MAGIC = 0x20534444;
  77598. var
  77599. //DDSD_CAPS = 0x1,
  77600. //DDSD_HEIGHT = 0x2,
  77601. //DDSD_WIDTH = 0x4,
  77602. //DDSD_PITCH = 0x8,
  77603. //DDSD_PIXELFORMAT = 0x1000,
  77604. DDSD_MIPMAPCOUNT = 0x20000;
  77605. //DDSD_LINEARSIZE = 0x80000,
  77606. //DDSD_DEPTH = 0x800000;
  77607. // var DDSCAPS_COMPLEX = 0x8,
  77608. // DDSCAPS_MIPMAP = 0x400000,
  77609. // DDSCAPS_TEXTURE = 0x1000;
  77610. var DDSCAPS2_CUBEMAP = 0x200;
  77611. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  77612. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  77613. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  77614. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  77615. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  77616. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  77617. // DDSCAPS2_VOLUME = 0x200000;
  77618. var
  77619. //DDPF_ALPHAPIXELS = 0x1,
  77620. //DDPF_ALPHA = 0x2,
  77621. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  77622. //DDPF_YUV = 0x200,
  77623. DDPF_LUMINANCE = 0x20000;
  77624. function FourCCToInt32(value) {
  77625. return value.charCodeAt(0) +
  77626. (value.charCodeAt(1) << 8) +
  77627. (value.charCodeAt(2) << 16) +
  77628. (value.charCodeAt(3) << 24);
  77629. }
  77630. function Int32ToFourCC(value) {
  77631. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  77632. }
  77633. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  77634. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  77635. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  77636. var FOURCC_DX10 = FourCCToInt32("DX10");
  77637. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  77638. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  77639. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  77640. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  77641. var headerLengthInt = 31; // The header length in 32 bit ints
  77642. // Offsets into the header array
  77643. var off_magic = 0;
  77644. var off_size = 1;
  77645. var off_flags = 2;
  77646. var off_height = 3;
  77647. var off_width = 4;
  77648. var off_mipmapCount = 7;
  77649. var off_pfFlags = 20;
  77650. var off_pfFourCC = 21;
  77651. var off_RGBbpp = 22;
  77652. var off_RMask = 23;
  77653. var off_GMask = 24;
  77654. var off_BMask = 25;
  77655. var off_AMask = 26;
  77656. // var off_caps1 = 27;
  77657. var off_caps2 = 28;
  77658. // var off_caps3 = 29;
  77659. // var off_caps4 = 30;
  77660. var off_dxgiFormat = 32;
  77661. ;
  77662. var DDSTools = /** @class */ (function () {
  77663. function DDSTools() {
  77664. }
  77665. DDSTools.GetDDSInfo = function (arrayBuffer) {
  77666. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  77667. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  77668. var mipmapCount = 1;
  77669. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  77670. mipmapCount = Math.max(1, header[off_mipmapCount]);
  77671. }
  77672. var fourCC = header[off_pfFourCC];
  77673. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  77674. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77675. switch (fourCC) {
  77676. case FOURCC_D3DFMT_R16G16B16A16F:
  77677. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77678. break;
  77679. case FOURCC_D3DFMT_R32G32B32A32F:
  77680. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77681. break;
  77682. case FOURCC_DX10:
  77683. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  77684. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77685. break;
  77686. }
  77687. }
  77688. return {
  77689. width: header[off_width],
  77690. height: header[off_height],
  77691. mipmapCount: mipmapCount,
  77692. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  77693. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  77694. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  77695. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  77696. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  77697. dxgiFormat: dxgiFormat,
  77698. textureType: textureType
  77699. };
  77700. };
  77701. DDSTools._ToHalfFloat = function (value) {
  77702. if (!DDSTools._FloatView) {
  77703. DDSTools._FloatView = new Float32Array(1);
  77704. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  77705. }
  77706. DDSTools._FloatView[0] = value;
  77707. var x = DDSTools._Int32View[0];
  77708. var bits = (x >> 16) & 0x8000; /* Get the sign */
  77709. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  77710. var e = (x >> 23) & 0xff; /* Using int is faster here */
  77711. /* If zero, or denormal, or exponent underflows too much for a denormal
  77712. * half, return signed zero. */
  77713. if (e < 103) {
  77714. return bits;
  77715. }
  77716. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  77717. if (e > 142) {
  77718. bits |= 0x7c00;
  77719. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  77720. * not Inf, so make sure we set one mantissa bit too. */
  77721. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  77722. return bits;
  77723. }
  77724. /* If exponent underflows but not too much, return a denormal */
  77725. if (e < 113) {
  77726. m |= 0x0800;
  77727. /* Extra rounding may overflow and set mantissa to 0 and exponent
  77728. * to 1, which is OK. */
  77729. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  77730. return bits;
  77731. }
  77732. bits |= ((e - 112) << 10) | (m >> 1);
  77733. bits += m & 1;
  77734. return bits;
  77735. };
  77736. DDSTools._FromHalfFloat = function (value) {
  77737. var s = (value & 0x8000) >> 15;
  77738. var e = (value & 0x7C00) >> 10;
  77739. var f = value & 0x03FF;
  77740. if (e === 0) {
  77741. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  77742. }
  77743. else if (e == 0x1F) {
  77744. return f ? NaN : ((s ? -1 : 1) * Infinity);
  77745. }
  77746. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  77747. };
  77748. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77749. var destArray = new Float32Array(dataLength);
  77750. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77751. var index = 0;
  77752. for (var y = 0; y < height; y++) {
  77753. for (var x = 0; x < width; x++) {
  77754. var srcPos = (x + y * width) * 4;
  77755. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  77756. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  77757. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  77758. if (DDSTools.StoreLODInAlphaChannel) {
  77759. destArray[index + 3] = lod;
  77760. }
  77761. else {
  77762. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  77763. }
  77764. index += 4;
  77765. }
  77766. }
  77767. return destArray;
  77768. };
  77769. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77770. if (DDSTools.StoreLODInAlphaChannel) {
  77771. var destArray = new Uint16Array(dataLength);
  77772. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77773. var index = 0;
  77774. for (var y = 0; y < height; y++) {
  77775. for (var x = 0; x < width; x++) {
  77776. var srcPos = (x + y * width) * 4;
  77777. destArray[index] = srcData[srcPos];
  77778. destArray[index + 1] = srcData[srcPos + 1];
  77779. destArray[index + 2] = srcData[srcPos + 2];
  77780. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  77781. index += 4;
  77782. }
  77783. }
  77784. return destArray;
  77785. }
  77786. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  77787. };
  77788. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77789. if (DDSTools.StoreLODInAlphaChannel) {
  77790. var destArray = new Float32Array(dataLength);
  77791. var srcData = new Float32Array(arrayBuffer, dataOffset);
  77792. var index = 0;
  77793. for (var y = 0; y < height; y++) {
  77794. for (var x = 0; x < width; x++) {
  77795. var srcPos = (x + y * width) * 4;
  77796. destArray[index] = srcData[srcPos];
  77797. destArray[index + 1] = srcData[srcPos + 1];
  77798. destArray[index + 2] = srcData[srcPos + 2];
  77799. destArray[index + 3] = lod;
  77800. index += 4;
  77801. }
  77802. }
  77803. return destArray;
  77804. }
  77805. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  77806. };
  77807. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77808. var destArray = new Uint8Array(dataLength);
  77809. var srcData = new Float32Array(arrayBuffer, dataOffset);
  77810. var index = 0;
  77811. for (var y = 0; y < height; y++) {
  77812. for (var x = 0; x < width; x++) {
  77813. var srcPos = (x + y * width) * 4;
  77814. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  77815. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  77816. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  77817. if (DDSTools.StoreLODInAlphaChannel) {
  77818. destArray[index + 3] = lod;
  77819. }
  77820. else {
  77821. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  77822. }
  77823. index += 4;
  77824. }
  77825. }
  77826. return destArray;
  77827. };
  77828. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77829. var destArray = new Uint8Array(dataLength);
  77830. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77831. var index = 0;
  77832. for (var y = 0; y < height; y++) {
  77833. for (var x = 0; x < width; x++) {
  77834. var srcPos = (x + y * width) * 4;
  77835. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  77836. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  77837. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  77838. if (DDSTools.StoreLODInAlphaChannel) {
  77839. destArray[index + 3] = lod;
  77840. }
  77841. else {
  77842. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  77843. }
  77844. index += 4;
  77845. }
  77846. }
  77847. return destArray;
  77848. };
  77849. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  77850. var byteArray = new Uint8Array(dataLength);
  77851. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  77852. var index = 0;
  77853. for (var y = 0; y < height; y++) {
  77854. for (var x = 0; x < width; x++) {
  77855. var srcPos = (x + y * width) * 4;
  77856. byteArray[index] = srcData[srcPos + rOffset];
  77857. byteArray[index + 1] = srcData[srcPos + gOffset];
  77858. byteArray[index + 2] = srcData[srcPos + bOffset];
  77859. byteArray[index + 3] = srcData[srcPos + aOffset];
  77860. index += 4;
  77861. }
  77862. }
  77863. return byteArray;
  77864. };
  77865. DDSTools._ExtractLongWordOrder = function (value) {
  77866. if (value === 0 || value === 255 || value === -16777216) {
  77867. return 0;
  77868. }
  77869. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  77870. };
  77871. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  77872. var byteArray = new Uint8Array(dataLength);
  77873. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  77874. var index = 0;
  77875. for (var y = 0; y < height; y++) {
  77876. for (var x = 0; x < width; x++) {
  77877. var srcPos = (x + y * width) * 3;
  77878. byteArray[index] = srcData[srcPos + rOffset];
  77879. byteArray[index + 1] = srcData[srcPos + gOffset];
  77880. byteArray[index + 2] = srcData[srcPos + bOffset];
  77881. index += 3;
  77882. }
  77883. }
  77884. return byteArray;
  77885. };
  77886. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  77887. var byteArray = new Uint8Array(dataLength);
  77888. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  77889. var index = 0;
  77890. for (var y = 0; y < height; y++) {
  77891. for (var x = 0; x < width; x++) {
  77892. var srcPos = (x + y * width);
  77893. byteArray[index] = srcData[srcPos];
  77894. index++;
  77895. }
  77896. }
  77897. return byteArray;
  77898. };
  77899. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  77900. if (lodIndex === void 0) { lodIndex = -1; }
  77901. var ext = engine.getCaps().s3tc;
  77902. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  77903. var fourCC, width, height, dataLength = 0, dataOffset;
  77904. var byteArray, mipmapCount, mip;
  77905. var internalFormat = 0;
  77906. var format = 0;
  77907. var blockBytes = 1;
  77908. if (header[off_magic] !== DDS_MAGIC) {
  77909. BABYLON.Tools.Error("Invalid magic number in DDS header");
  77910. return;
  77911. }
  77912. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  77913. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  77914. return;
  77915. }
  77916. if (info.isCompressed && !ext) {
  77917. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  77918. return;
  77919. }
  77920. var bpp = header[off_RGBbpp];
  77921. dataOffset = header[off_size] + 4;
  77922. var computeFormats = false;
  77923. if (info.isFourCC) {
  77924. fourCC = header[off_pfFourCC];
  77925. switch (fourCC) {
  77926. case FOURCC_DXT1:
  77927. blockBytes = 8;
  77928. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  77929. break;
  77930. case FOURCC_DXT3:
  77931. blockBytes = 16;
  77932. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  77933. break;
  77934. case FOURCC_DXT5:
  77935. blockBytes = 16;
  77936. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  77937. break;
  77938. case FOURCC_D3DFMT_R16G16B16A16F:
  77939. computeFormats = true;
  77940. break;
  77941. case FOURCC_D3DFMT_R32G32B32A32F:
  77942. computeFormats = true;
  77943. break;
  77944. case FOURCC_DX10:
  77945. // There is an additionnal header so dataOffset need to be changed
  77946. dataOffset += 5 * 4; // 5 uints
  77947. var supported = false;
  77948. switch (info.dxgiFormat) {
  77949. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  77950. computeFormats = true;
  77951. supported = true;
  77952. break;
  77953. case DXGI_FORMAT_B8G8R8X8_UNORM:
  77954. info.isRGB = true;
  77955. info.isFourCC = false;
  77956. bpp = 32;
  77957. supported = true;
  77958. break;
  77959. }
  77960. if (supported) {
  77961. break;
  77962. }
  77963. default:
  77964. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  77965. return;
  77966. }
  77967. }
  77968. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  77969. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  77970. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  77971. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  77972. if (computeFormats) {
  77973. format = engine._getWebGLTextureType(info.textureType);
  77974. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  77975. }
  77976. mipmapCount = 1;
  77977. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  77978. mipmapCount = Math.max(1, header[off_mipmapCount]);
  77979. }
  77980. for (var face = 0; face < faces; face++) {
  77981. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  77982. width = header[off_width];
  77983. height = header[off_height];
  77984. for (mip = 0; mip < mipmapCount; ++mip) {
  77985. if (lodIndex === -1 || lodIndex === mip) {
  77986. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  77987. var i = (lodIndex === -1) ? mip : 0;
  77988. if (!info.isCompressed && info.isFourCC) {
  77989. dataLength = width * height * 4;
  77990. var floatArray = null;
  77991. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  77992. if (bpp === 128) {
  77993. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77994. }
  77995. else if (bpp === 64) {
  77996. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77997. }
  77998. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77999. format = engine._getWebGLTextureType(info.textureType);
  78000. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  78001. }
  78002. else {
  78003. if (bpp === 128) {
  78004. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78005. }
  78006. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  78007. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78008. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  78009. format = engine._getWebGLTextureType(info.textureType);
  78010. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  78011. }
  78012. else {
  78013. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78014. }
  78015. }
  78016. if (floatArray) {
  78017. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  78018. }
  78019. }
  78020. else if (info.isRGB) {
  78021. if (bpp === 24) {
  78022. dataLength = width * height * 3;
  78023. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  78024. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  78025. }
  78026. else {
  78027. dataLength = width * height * 4;
  78028. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  78029. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  78030. }
  78031. }
  78032. else if (info.isLuminance) {
  78033. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  78034. var unpaddedRowSize = width;
  78035. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  78036. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  78037. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  78038. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  78039. }
  78040. else {
  78041. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  78042. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  78043. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  78044. }
  78045. }
  78046. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  78047. width *= 0.5;
  78048. height *= 0.5;
  78049. width = Math.max(1.0, width);
  78050. height = Math.max(1.0, height);
  78051. }
  78052. if (currentFace !== undefined) {
  78053. // Loading a single face
  78054. break;
  78055. }
  78056. }
  78057. };
  78058. DDSTools.StoreLODInAlphaChannel = false;
  78059. return DDSTools;
  78060. }());
  78061. BABYLON.DDSTools = DDSTools;
  78062. })(BABYLON || (BABYLON = {}));
  78063. //# sourceMappingURL=babylon.dds.js.map
  78064. var BABYLON;
  78065. (function (BABYLON) {
  78066. /**
  78067. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  78068. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  78069. */
  78070. var KhronosTextureContainer = /** @class */ (function () {
  78071. /**
  78072. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  78073. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  78074. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  78075. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  78076. */
  78077. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  78078. this.arrayBuffer = arrayBuffer;
  78079. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  78080. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  78081. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  78082. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  78083. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  78084. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  78085. BABYLON.Tools.Error("texture missing KTX identifier");
  78086. return;
  78087. }
  78088. // load the reset of the header in native 32 bit int
  78089. var header = new Int32Array(this.arrayBuffer, 12, 13);
  78090. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  78091. var oppositeEndianess = header[0] === 0x01020304;
  78092. // read all the header elements in order they exist in the file, without modification (sans endainness)
  78093. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  78094. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  78095. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  78096. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  78097. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  78098. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  78099. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  78100. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  78101. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  78102. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  78103. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  78104. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  78105. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  78106. if (this.glType !== 0) {
  78107. BABYLON.Tools.Error("only compressed formats currently supported");
  78108. return;
  78109. }
  78110. else {
  78111. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  78112. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  78113. }
  78114. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  78115. BABYLON.Tools.Error("only 2D textures currently supported");
  78116. return;
  78117. }
  78118. if (this.numberOfArrayElements !== 0) {
  78119. BABYLON.Tools.Error("texture arrays not currently supported");
  78120. return;
  78121. }
  78122. if (this.numberOfFaces !== facesExpected) {
  78123. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  78124. return;
  78125. }
  78126. // we now have a completely validated file, so could use existence of loadType as success
  78127. // would need to make this more elaborate & adjust checks above to support more than one load type
  78128. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  78129. }
  78130. // not as fast hardware based, but will probably never need to use
  78131. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  78132. return ((val & 0xFF) << 24)
  78133. | ((val & 0xFF00) << 8)
  78134. | ((val >> 8) & 0xFF00)
  78135. | ((val >> 24) & 0xFF);
  78136. };
  78137. /**
  78138. * It is assumed that the texture has already been created & is currently bound
  78139. */
  78140. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  78141. switch (this.loadType) {
  78142. case KhronosTextureContainer.COMPRESSED_2D:
  78143. this._upload2DCompressedLevels(gl, loadMipmaps);
  78144. break;
  78145. case KhronosTextureContainer.TEX_2D:
  78146. case KhronosTextureContainer.COMPRESSED_3D:
  78147. case KhronosTextureContainer.TEX_3D:
  78148. }
  78149. };
  78150. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  78151. // initialize width & height for level 1
  78152. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  78153. var width = this.pixelWidth;
  78154. var height = this.pixelHeight;
  78155. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  78156. for (var level = 0; level < mipmapCount; level++) {
  78157. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  78158. for (var face = 0; face < this.numberOfFaces; face++) {
  78159. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  78160. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  78161. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  78162. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  78163. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  78164. }
  78165. width = Math.max(1.0, width * 0.5);
  78166. height = Math.max(1.0, height * 0.5);
  78167. }
  78168. };
  78169. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  78170. // load types
  78171. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  78172. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  78173. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  78174. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  78175. return KhronosTextureContainer;
  78176. }());
  78177. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  78178. })(BABYLON || (BABYLON = {}));
  78179. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  78180. var BABYLON;
  78181. (function (BABYLON) {
  78182. var Debug = /** @class */ (function () {
  78183. function Debug() {
  78184. }
  78185. Debug.AxesViewer = /** @class */ (function () {
  78186. function AxesViewer(scene, scaleLines) {
  78187. if (scaleLines === void 0) { scaleLines = 1; }
  78188. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78189. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78190. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78191. this.scaleLines = 1;
  78192. this.scaleLines = scaleLines;
  78193. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  78194. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  78195. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  78196. this._xmesh.renderingGroupId = 2;
  78197. this._ymesh.renderingGroupId = 2;
  78198. this._zmesh.renderingGroupId = 2;
  78199. this._xmesh.material.checkReadyOnlyOnce = true;
  78200. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  78201. this._ymesh.material.checkReadyOnlyOnce = true;
  78202. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  78203. this._zmesh.material.checkReadyOnlyOnce = true;
  78204. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  78205. this.scene = scene;
  78206. }
  78207. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  78208. var scaleLines = this.scaleLines;
  78209. if (this._xmesh) {
  78210. this._xmesh.position.copyFrom(position);
  78211. }
  78212. if (this._ymesh) {
  78213. this._ymesh.position.copyFrom(position);
  78214. }
  78215. if (this._zmesh) {
  78216. this._zmesh.position.copyFrom(position);
  78217. }
  78218. var point2 = this._xline[1];
  78219. point2.x = xaxis.x * scaleLines;
  78220. point2.y = xaxis.y * scaleLines;
  78221. point2.z = xaxis.z * scaleLines;
  78222. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  78223. point2 = this._yline[1];
  78224. point2.x = yaxis.x * scaleLines;
  78225. point2.y = yaxis.y * scaleLines;
  78226. point2.z = yaxis.z * scaleLines;
  78227. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  78228. point2 = this._zline[1];
  78229. point2.x = zaxis.x * scaleLines;
  78230. point2.y = zaxis.y * scaleLines;
  78231. point2.z = zaxis.z * scaleLines;
  78232. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  78233. };
  78234. AxesViewer.prototype.dispose = function () {
  78235. if (this._xmesh) {
  78236. this._xmesh.dispose();
  78237. }
  78238. if (this._ymesh) {
  78239. this._ymesh.dispose();
  78240. }
  78241. if (this._zmesh) {
  78242. this._zmesh.dispose();
  78243. }
  78244. this._xmesh = null;
  78245. this._ymesh = null;
  78246. this._zmesh = null;
  78247. this.scene = null;
  78248. };
  78249. return AxesViewer;
  78250. }());
  78251. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  78252. __extends(BoneAxesViewer, _super);
  78253. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  78254. if (scaleLines === void 0) { scaleLines = 1; }
  78255. var _this = _super.call(this, scene, scaleLines) || this;
  78256. _this.pos = BABYLON.Vector3.Zero();
  78257. _this.xaxis = BABYLON.Vector3.Zero();
  78258. _this.yaxis = BABYLON.Vector3.Zero();
  78259. _this.zaxis = BABYLON.Vector3.Zero();
  78260. _this.mesh = mesh;
  78261. _this.bone = bone;
  78262. return _this;
  78263. }
  78264. BoneAxesViewer.prototype.update = function () {
  78265. if (!this.mesh || !this.bone) {
  78266. return;
  78267. }
  78268. var bone = this.bone;
  78269. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  78270. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  78271. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  78272. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  78273. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  78274. };
  78275. BoneAxesViewer.prototype.dispose = function () {
  78276. if (this.mesh) {
  78277. this.mesh = null;
  78278. this.bone = null;
  78279. _super.prototype.dispose.call(this);
  78280. }
  78281. };
  78282. return BoneAxesViewer;
  78283. }(Debug.AxesViewer));
  78284. Debug.PhysicsViewer = /** @class */ (function () {
  78285. function PhysicsViewer(scene) {
  78286. this._impostors = [];
  78287. this._meshes = [];
  78288. this._numMeshes = 0;
  78289. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  78290. var physicEngine = this._scene.getPhysicsEngine();
  78291. if (physicEngine) {
  78292. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  78293. }
  78294. }
  78295. PhysicsViewer.prototype._updateDebugMeshes = function () {
  78296. var plugin = this._physicsEnginePlugin;
  78297. for (var i = 0; i < this._numMeshes; i++) {
  78298. var impostor = this._impostors[i];
  78299. if (!impostor) {
  78300. continue;
  78301. }
  78302. if (impostor.isDisposed) {
  78303. this.hideImpostor(this._impostors[i--]);
  78304. }
  78305. else {
  78306. var mesh = this._meshes[i];
  78307. if (mesh && plugin) {
  78308. plugin.syncMeshWithImpostor(mesh, impostor);
  78309. }
  78310. }
  78311. }
  78312. };
  78313. PhysicsViewer.prototype.showImpostor = function (impostor) {
  78314. if (!this._scene) {
  78315. return;
  78316. }
  78317. for (var i = 0; i < this._numMeshes; i++) {
  78318. if (this._impostors[i] == impostor) {
  78319. return;
  78320. }
  78321. }
  78322. var debugMesh = this._getDebugMesh(impostor, this._scene);
  78323. if (debugMesh) {
  78324. this._impostors[this._numMeshes] = impostor;
  78325. this._meshes[this._numMeshes] = debugMesh;
  78326. if (this._numMeshes === 0) {
  78327. this._renderFunction = this._updateDebugMeshes.bind(this);
  78328. this._scene.registerBeforeRender(this._renderFunction);
  78329. }
  78330. this._numMeshes++;
  78331. }
  78332. };
  78333. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  78334. if (!impostor || !this._scene) {
  78335. return;
  78336. }
  78337. var removed = false;
  78338. for (var i = 0; i < this._numMeshes; i++) {
  78339. if (this._impostors[i] == impostor) {
  78340. var mesh = this._meshes[i];
  78341. if (!mesh) {
  78342. continue;
  78343. }
  78344. this._scene.removeMesh(mesh);
  78345. mesh.dispose();
  78346. this._numMeshes--;
  78347. if (this._numMeshes > 0) {
  78348. this._meshes[i] = this._meshes[this._numMeshes];
  78349. this._impostors[i] = this._impostors[this._numMeshes];
  78350. this._meshes[this._numMeshes] = null;
  78351. this._impostors[this._numMeshes] = null;
  78352. }
  78353. else {
  78354. this._meshes[0] = null;
  78355. this._impostors[0] = null;
  78356. }
  78357. removed = true;
  78358. break;
  78359. }
  78360. }
  78361. if (removed && this._numMeshes === 0) {
  78362. this._scene.unregisterBeforeRender(this._renderFunction);
  78363. }
  78364. };
  78365. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  78366. if (!this._debugMaterial) {
  78367. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  78368. this._debugMaterial.wireframe = true;
  78369. }
  78370. return this._debugMaterial;
  78371. };
  78372. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  78373. if (!this._debugBoxMesh) {
  78374. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  78375. this._debugBoxMesh.renderingGroupId = 1;
  78376. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  78377. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  78378. scene.removeMesh(this._debugBoxMesh);
  78379. }
  78380. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  78381. };
  78382. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  78383. if (!this._debugSphereMesh) {
  78384. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  78385. this._debugSphereMesh.renderingGroupId = 1;
  78386. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  78387. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  78388. scene.removeMesh(this._debugSphereMesh);
  78389. }
  78390. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  78391. };
  78392. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  78393. var mesh = null;
  78394. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  78395. mesh = this._getDebugBoxMesh(scene);
  78396. impostor.getBoxSizeToRef(mesh.scaling);
  78397. }
  78398. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  78399. mesh = this._getDebugSphereMesh(scene);
  78400. var radius = impostor.getRadius();
  78401. mesh.scaling.x = radius * 2;
  78402. mesh.scaling.y = radius * 2;
  78403. mesh.scaling.z = radius * 2;
  78404. }
  78405. return mesh;
  78406. };
  78407. PhysicsViewer.prototype.dispose = function () {
  78408. for (var i = 0; i < this._numMeshes; i++) {
  78409. this.hideImpostor(this._impostors[i]);
  78410. }
  78411. if (this._debugBoxMesh) {
  78412. this._debugBoxMesh.dispose();
  78413. }
  78414. if (this._debugSphereMesh) {
  78415. this._debugSphereMesh.dispose();
  78416. }
  78417. if (this._debugMaterial) {
  78418. this._debugMaterial.dispose();
  78419. }
  78420. this._impostors.length = 0;
  78421. this._scene = null;
  78422. this._physicsEnginePlugin = null;
  78423. };
  78424. return PhysicsViewer;
  78425. }());
  78426. Debug.SkeletonViewer = /** @class */ (function () {
  78427. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  78428. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  78429. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  78430. this.skeleton = skeleton;
  78431. this.mesh = mesh;
  78432. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  78433. this.renderingGroupId = renderingGroupId;
  78434. this.color = BABYLON.Color3.White();
  78435. this._debugLines = new Array();
  78436. this._isEnabled = false;
  78437. this._scene = scene;
  78438. this.update();
  78439. this._renderFunction = this.update.bind(this);
  78440. }
  78441. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  78442. get: function () {
  78443. return this._isEnabled;
  78444. },
  78445. set: function (value) {
  78446. if (this._isEnabled === value) {
  78447. return;
  78448. }
  78449. this._isEnabled = value;
  78450. if (value) {
  78451. this._scene.registerBeforeRender(this._renderFunction);
  78452. }
  78453. else {
  78454. this._scene.unregisterBeforeRender(this._renderFunction);
  78455. }
  78456. },
  78457. enumerable: true,
  78458. configurable: true
  78459. });
  78460. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  78461. if (x === void 0) { x = 0; }
  78462. if (y === void 0) { y = 0; }
  78463. if (z === void 0) { z = 0; }
  78464. var tmat = BABYLON.Tmp.Matrix[0];
  78465. var parentBone = bone.getParent();
  78466. tmat.copyFrom(bone.getLocalMatrix());
  78467. if (x !== 0 || y !== 0 || z !== 0) {
  78468. var tmat2 = BABYLON.Tmp.Matrix[1];
  78469. BABYLON.Matrix.IdentityToRef(tmat2);
  78470. tmat2.m[12] = x;
  78471. tmat2.m[13] = y;
  78472. tmat2.m[14] = z;
  78473. tmat2.multiplyToRef(tmat, tmat);
  78474. }
  78475. if (parentBone) {
  78476. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  78477. }
  78478. tmat.multiplyToRef(meshMat, tmat);
  78479. position.x = tmat.m[12];
  78480. position.y = tmat.m[13];
  78481. position.z = tmat.m[14];
  78482. };
  78483. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  78484. var len = bones.length;
  78485. var meshPos = this.mesh.position;
  78486. for (var i = 0; i < len; i++) {
  78487. var bone = bones[i];
  78488. var points = this._debugLines[i];
  78489. if (!points) {
  78490. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78491. this._debugLines[i] = points;
  78492. }
  78493. this._getBonePosition(points[0], bone, meshMat);
  78494. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  78495. points[0].subtractInPlace(meshPos);
  78496. points[1].subtractInPlace(meshPos);
  78497. }
  78498. };
  78499. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  78500. var len = bones.length;
  78501. var boneNum = 0;
  78502. var meshPos = this.mesh.position;
  78503. for (var i = len - 1; i >= 0; i--) {
  78504. var childBone = bones[i];
  78505. var parentBone = childBone.getParent();
  78506. if (!parentBone) {
  78507. continue;
  78508. }
  78509. var points = this._debugLines[boneNum];
  78510. if (!points) {
  78511. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78512. this._debugLines[boneNum] = points;
  78513. }
  78514. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  78515. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  78516. points[0].subtractInPlace(meshPos);
  78517. points[1].subtractInPlace(meshPos);
  78518. boneNum++;
  78519. }
  78520. };
  78521. SkeletonViewer.prototype.update = function () {
  78522. if (this.autoUpdateBonesMatrices) {
  78523. this.skeleton.computeAbsoluteTransforms();
  78524. }
  78525. if (this.skeleton.bones[0].length === undefined) {
  78526. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  78527. }
  78528. else {
  78529. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  78530. }
  78531. if (!this._debugMesh) {
  78532. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  78533. this._debugMesh.renderingGroupId = this.renderingGroupId;
  78534. }
  78535. else {
  78536. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  78537. }
  78538. this._debugMesh.position.copyFrom(this.mesh.position);
  78539. this._debugMesh.color = this.color;
  78540. };
  78541. SkeletonViewer.prototype.dispose = function () {
  78542. if (this._debugMesh) {
  78543. this.isEnabled = false;
  78544. this._debugMesh.dispose();
  78545. this._debugMesh = null;
  78546. }
  78547. };
  78548. return SkeletonViewer;
  78549. }());
  78550. return Debug;
  78551. }());
  78552. BABYLON.Debug = Debug;
  78553. })(BABYLON || (BABYLON = {}));
  78554. //# sourceMappingURL=babylon.debugModules.js.map
  78555. var BABYLON;
  78556. (function (BABYLON) {
  78557. var RayHelper = /** @class */ (function () {
  78558. function RayHelper(ray) {
  78559. this.ray = ray;
  78560. }
  78561. RayHelper.CreateAndShow = function (ray, scene, color) {
  78562. var helper = new RayHelper(ray);
  78563. helper.show(scene, color);
  78564. return helper;
  78565. };
  78566. RayHelper.prototype.show = function (scene, color) {
  78567. if (!this._renderFunction && this.ray) {
  78568. var ray = this.ray;
  78569. this._renderFunction = this._render.bind(this);
  78570. this._scene = scene;
  78571. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  78572. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  78573. if (this._renderFunction) {
  78574. this._scene.registerBeforeRender(this._renderFunction);
  78575. }
  78576. }
  78577. if (color && this._renderLine) {
  78578. this._renderLine.color.copyFrom(color);
  78579. }
  78580. };
  78581. RayHelper.prototype.hide = function () {
  78582. if (this._renderFunction && this._scene) {
  78583. this._scene.unregisterBeforeRender(this._renderFunction);
  78584. this._scene = null;
  78585. this._renderFunction = null;
  78586. if (this._renderLine) {
  78587. this._renderLine.dispose();
  78588. this._renderLine = null;
  78589. }
  78590. this._renderPoints = [];
  78591. }
  78592. };
  78593. RayHelper.prototype._render = function () {
  78594. var ray = this.ray;
  78595. if (!ray) {
  78596. return;
  78597. }
  78598. var point = this._renderPoints[1];
  78599. var len = Math.min(ray.length, 1000000);
  78600. point.copyFrom(ray.direction);
  78601. point.scaleInPlace(len);
  78602. point.addInPlace(ray.origin);
  78603. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  78604. };
  78605. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  78606. this._attachedToMesh = mesh;
  78607. var ray = this.ray;
  78608. if (!ray) {
  78609. return;
  78610. }
  78611. if (!ray.direction) {
  78612. ray.direction = BABYLON.Vector3.Zero();
  78613. }
  78614. if (!ray.origin) {
  78615. ray.origin = BABYLON.Vector3.Zero();
  78616. }
  78617. if (length) {
  78618. ray.length = length;
  78619. }
  78620. if (!meshSpaceOrigin) {
  78621. meshSpaceOrigin = BABYLON.Vector3.Zero();
  78622. }
  78623. if (!meshSpaceDirection) {
  78624. // -1 so that this will work with Mesh.lookAt
  78625. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  78626. }
  78627. if (!this._meshSpaceDirection) {
  78628. this._meshSpaceDirection = meshSpaceDirection.clone();
  78629. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  78630. }
  78631. else {
  78632. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  78633. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  78634. }
  78635. if (!this._updateToMeshFunction) {
  78636. this._updateToMeshFunction = this._updateToMesh.bind(this);
  78637. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  78638. }
  78639. this._updateToMesh();
  78640. };
  78641. RayHelper.prototype.detachFromMesh = function () {
  78642. if (this._attachedToMesh) {
  78643. if (this._updateToMeshFunction) {
  78644. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  78645. }
  78646. this._attachedToMesh = null;
  78647. this._updateToMeshFunction = null;
  78648. }
  78649. };
  78650. RayHelper.prototype._updateToMesh = function () {
  78651. var ray = this.ray;
  78652. if (!this._attachedToMesh || !ray) {
  78653. return;
  78654. }
  78655. if (this._attachedToMesh._isDisposed) {
  78656. this.detachFromMesh();
  78657. return;
  78658. }
  78659. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  78660. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  78661. };
  78662. RayHelper.prototype.dispose = function () {
  78663. this.hide();
  78664. this.detachFromMesh();
  78665. this.ray = null;
  78666. };
  78667. return RayHelper;
  78668. }());
  78669. BABYLON.RayHelper = RayHelper;
  78670. })(BABYLON || (BABYLON = {}));
  78671. //# sourceMappingURL=babylon.rayHelper.js.map
  78672. var BABYLON;
  78673. (function (BABYLON) {
  78674. // load the inspector using require, if not present in the global namespace.
  78675. var DebugLayer = /** @class */ (function () {
  78676. function DebugLayer(scene) {
  78677. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  78678. this._scene = scene;
  78679. // load inspector using require, if it doesn't exist on the global namespace.
  78680. }
  78681. /** Creates the inspector window. */
  78682. DebugLayer.prototype._createInspector = function (config) {
  78683. if (config === void 0) { config = {}; }
  78684. var popup = config.popup || false;
  78685. var initialTab = config.initialTab || 0;
  78686. var parentElement = config.parentElement || null;
  78687. if (!this._inspector) {
  78688. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  78689. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  78690. } // else nothing to do,; instance is already existing
  78691. };
  78692. DebugLayer.prototype.isVisible = function () {
  78693. if (!this._inspector) {
  78694. return false;
  78695. }
  78696. return true;
  78697. };
  78698. DebugLayer.prototype.hide = function () {
  78699. if (this._inspector) {
  78700. try {
  78701. this._inspector.dispose();
  78702. }
  78703. catch (e) {
  78704. // If the inspector has been removed directly from the inspector tool
  78705. }
  78706. this._inspector = null;
  78707. }
  78708. };
  78709. DebugLayer.prototype.show = function (config) {
  78710. if (config === void 0) { config = {}; }
  78711. if (typeof this.BJSINSPECTOR == 'undefined') {
  78712. // Load inspector and add it to the DOM
  78713. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  78714. }
  78715. else {
  78716. // Otherwise creates the inspector
  78717. this._createInspector(config);
  78718. }
  78719. };
  78720. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  78721. return DebugLayer;
  78722. }());
  78723. BABYLON.DebugLayer = DebugLayer;
  78724. })(BABYLON || (BABYLON = {}));
  78725. //# sourceMappingURL=babylon.debugLayer.js.map
  78726. var BABYLON;
  78727. (function (BABYLON) {
  78728. var BoundingBoxRenderer = /** @class */ (function () {
  78729. function BoundingBoxRenderer(scene) {
  78730. this.frontColor = new BABYLON.Color3(1, 1, 1);
  78731. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  78732. this.showBackLines = true;
  78733. this.renderList = new BABYLON.SmartArray(32);
  78734. this._vertexBuffers = {};
  78735. this._scene = scene;
  78736. }
  78737. BoundingBoxRenderer.prototype._prepareRessources = function () {
  78738. if (this._colorShader) {
  78739. return;
  78740. }
  78741. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  78742. attributes: [BABYLON.VertexBuffer.PositionKind],
  78743. uniforms: ["world", "viewProjection", "color"]
  78744. });
  78745. var engine = this._scene.getEngine();
  78746. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  78747. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  78748. this._createIndexBuffer();
  78749. };
  78750. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  78751. var engine = this._scene.getEngine();
  78752. 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]);
  78753. };
  78754. BoundingBoxRenderer.prototype._rebuild = function () {
  78755. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78756. if (vb) {
  78757. vb._rebuild();
  78758. }
  78759. this._createIndexBuffer();
  78760. };
  78761. BoundingBoxRenderer.prototype.reset = function () {
  78762. this.renderList.reset();
  78763. };
  78764. BoundingBoxRenderer.prototype.render = function () {
  78765. if (this.renderList.length === 0) {
  78766. return;
  78767. }
  78768. this._prepareRessources();
  78769. if (!this._colorShader.isReady()) {
  78770. return;
  78771. }
  78772. var engine = this._scene.getEngine();
  78773. engine.setDepthWrite(false);
  78774. this._colorShader._preBind();
  78775. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  78776. var boundingBox = this.renderList.data[boundingBoxIndex];
  78777. var min = boundingBox.minimum;
  78778. var max = boundingBox.maximum;
  78779. var diff = max.subtract(min);
  78780. var median = min.add(diff.scale(0.5));
  78781. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  78782. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  78783. .multiply(boundingBox.getWorldMatrix());
  78784. // VBOs
  78785. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  78786. if (this.showBackLines) {
  78787. // Back
  78788. engine.setDepthFunctionToGreaterOrEqual();
  78789. this._scene.resetCachedMaterial();
  78790. this._colorShader.setColor4("color", this.backColor.toColor4());
  78791. this._colorShader.bind(worldMatrix);
  78792. // Draw order
  78793. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  78794. }
  78795. // Front
  78796. engine.setDepthFunctionToLess();
  78797. this._scene.resetCachedMaterial();
  78798. this._colorShader.setColor4("color", this.frontColor.toColor4());
  78799. this._colorShader.bind(worldMatrix);
  78800. // Draw order
  78801. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  78802. }
  78803. this._colorShader.unbind();
  78804. engine.setDepthFunctionToLessOrEqual();
  78805. engine.setDepthWrite(true);
  78806. };
  78807. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  78808. this._prepareRessources();
  78809. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  78810. return;
  78811. }
  78812. var engine = this._scene.getEngine();
  78813. engine.setDepthWrite(false);
  78814. engine.setColorWrite(false);
  78815. this._colorShader._preBind();
  78816. var boundingBox = mesh._boundingInfo.boundingBox;
  78817. var min = boundingBox.minimum;
  78818. var max = boundingBox.maximum;
  78819. var diff = max.subtract(min);
  78820. var median = min.add(diff.scale(0.5));
  78821. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  78822. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  78823. .multiply(boundingBox.getWorldMatrix());
  78824. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  78825. engine.setDepthFunctionToLess();
  78826. this._scene.resetCachedMaterial();
  78827. this._colorShader.bind(worldMatrix);
  78828. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  78829. this._colorShader.unbind();
  78830. engine.setDepthFunctionToLessOrEqual();
  78831. engine.setDepthWrite(true);
  78832. engine.setColorWrite(true);
  78833. };
  78834. BoundingBoxRenderer.prototype.dispose = function () {
  78835. if (!this._colorShader) {
  78836. return;
  78837. }
  78838. this.renderList.dispose();
  78839. this._colorShader.dispose();
  78840. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78841. if (buffer) {
  78842. buffer.dispose();
  78843. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  78844. }
  78845. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  78846. };
  78847. return BoundingBoxRenderer;
  78848. }());
  78849. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  78850. })(BABYLON || (BABYLON = {}));
  78851. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  78852. var BABYLON;
  78853. (function (BABYLON) {
  78854. var MorphTarget = /** @class */ (function () {
  78855. function MorphTarget(name, influence) {
  78856. if (influence === void 0) { influence = 0; }
  78857. this.name = name;
  78858. this.animations = new Array();
  78859. this._positions = null;
  78860. this._normals = null;
  78861. this._tangents = null;
  78862. this.onInfluenceChanged = new BABYLON.Observable();
  78863. this.influence = influence;
  78864. }
  78865. Object.defineProperty(MorphTarget.prototype, "influence", {
  78866. get: function () {
  78867. return this._influence;
  78868. },
  78869. set: function (influence) {
  78870. if (this._influence === influence) {
  78871. return;
  78872. }
  78873. var previous = this._influence;
  78874. this._influence = influence;
  78875. if (this.onInfluenceChanged.hasObservers) {
  78876. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  78877. }
  78878. },
  78879. enumerable: true,
  78880. configurable: true
  78881. });
  78882. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  78883. get: function () {
  78884. return !!this._positions;
  78885. },
  78886. enumerable: true,
  78887. configurable: true
  78888. });
  78889. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  78890. get: function () {
  78891. return !!this._normals;
  78892. },
  78893. enumerable: true,
  78894. configurable: true
  78895. });
  78896. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  78897. get: function () {
  78898. return !!this._tangents;
  78899. },
  78900. enumerable: true,
  78901. configurable: true
  78902. });
  78903. MorphTarget.prototype.setPositions = function (data) {
  78904. this._positions = data;
  78905. };
  78906. MorphTarget.prototype.getPositions = function () {
  78907. return this._positions;
  78908. };
  78909. MorphTarget.prototype.setNormals = function (data) {
  78910. this._normals = data;
  78911. };
  78912. MorphTarget.prototype.getNormals = function () {
  78913. return this._normals;
  78914. };
  78915. MorphTarget.prototype.setTangents = function (data) {
  78916. this._tangents = data;
  78917. };
  78918. MorphTarget.prototype.getTangents = function () {
  78919. return this._tangents;
  78920. };
  78921. /**
  78922. * Serializes the current target into a Serialization object.
  78923. * Returns the serialized object.
  78924. */
  78925. MorphTarget.prototype.serialize = function () {
  78926. var serializationObject = {};
  78927. serializationObject.name = this.name;
  78928. serializationObject.influence = this.influence;
  78929. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  78930. if (this.hasNormals) {
  78931. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  78932. }
  78933. if (this.hasTangents) {
  78934. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  78935. }
  78936. // Animations
  78937. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  78938. return serializationObject;
  78939. };
  78940. // Statics
  78941. MorphTarget.Parse = function (serializationObject) {
  78942. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  78943. result.setPositions(serializationObject.positions);
  78944. if (serializationObject.normals) {
  78945. result.setNormals(serializationObject.normals);
  78946. }
  78947. if (serializationObject.tangents) {
  78948. result.setTangents(serializationObject.tangents);
  78949. }
  78950. // Animations
  78951. if (serializationObject.animations) {
  78952. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  78953. var parsedAnimation = serializationObject.animations[animationIndex];
  78954. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  78955. }
  78956. }
  78957. return result;
  78958. };
  78959. MorphTarget.FromMesh = function (mesh, name, influence) {
  78960. if (!name) {
  78961. name = mesh.name;
  78962. }
  78963. var result = new MorphTarget(name, influence);
  78964. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  78965. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  78966. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  78967. }
  78968. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  78969. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  78970. }
  78971. return result;
  78972. };
  78973. return MorphTarget;
  78974. }());
  78975. BABYLON.MorphTarget = MorphTarget;
  78976. })(BABYLON || (BABYLON = {}));
  78977. //# sourceMappingURL=babylon.morphTarget.js.map
  78978. var BABYLON;
  78979. (function (BABYLON) {
  78980. var MorphTargetManager = /** @class */ (function () {
  78981. function MorphTargetManager(scene) {
  78982. if (scene === void 0) { scene = null; }
  78983. this._targets = new Array();
  78984. this._targetObservable = new Array();
  78985. this._activeTargets = new BABYLON.SmartArray(16);
  78986. this._supportsNormals = false;
  78987. this._supportsTangents = false;
  78988. this._vertexCount = 0;
  78989. this._uniqueId = 0;
  78990. this._tempInfluences = new Array();
  78991. if (!scene) {
  78992. scene = BABYLON.Engine.LastCreatedScene;
  78993. }
  78994. this._scene = scene;
  78995. if (this._scene) {
  78996. this._scene.morphTargetManagers.push(this);
  78997. this._uniqueId = this._scene.getUniqueId();
  78998. }
  78999. }
  79000. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  79001. get: function () {
  79002. return this._uniqueId;
  79003. },
  79004. enumerable: true,
  79005. configurable: true
  79006. });
  79007. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  79008. get: function () {
  79009. return this._vertexCount;
  79010. },
  79011. enumerable: true,
  79012. configurable: true
  79013. });
  79014. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  79015. get: function () {
  79016. return this._supportsNormals;
  79017. },
  79018. enumerable: true,
  79019. configurable: true
  79020. });
  79021. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  79022. get: function () {
  79023. return this._supportsTangents;
  79024. },
  79025. enumerable: true,
  79026. configurable: true
  79027. });
  79028. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  79029. get: function () {
  79030. return this._targets.length;
  79031. },
  79032. enumerable: true,
  79033. configurable: true
  79034. });
  79035. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  79036. get: function () {
  79037. return this._activeTargets.length;
  79038. },
  79039. enumerable: true,
  79040. configurable: true
  79041. });
  79042. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  79043. get: function () {
  79044. return this._influences;
  79045. },
  79046. enumerable: true,
  79047. configurable: true
  79048. });
  79049. MorphTargetManager.prototype.getActiveTarget = function (index) {
  79050. return this._activeTargets.data[index];
  79051. };
  79052. MorphTargetManager.prototype.getTarget = function (index) {
  79053. return this._targets[index];
  79054. };
  79055. MorphTargetManager.prototype.addTarget = function (target) {
  79056. var _this = this;
  79057. this._targets.push(target);
  79058. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  79059. _this._syncActiveTargets(needUpdate);
  79060. }));
  79061. this._syncActiveTargets(true);
  79062. };
  79063. MorphTargetManager.prototype.removeTarget = function (target) {
  79064. var index = this._targets.indexOf(target);
  79065. if (index >= 0) {
  79066. this._targets.splice(index, 1);
  79067. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  79068. this._syncActiveTargets(true);
  79069. }
  79070. };
  79071. /**
  79072. * Serializes the current manager into a Serialization object.
  79073. * Returns the serialized object.
  79074. */
  79075. MorphTargetManager.prototype.serialize = function () {
  79076. var serializationObject = {};
  79077. serializationObject.id = this.uniqueId;
  79078. serializationObject.targets = [];
  79079. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  79080. var target = _a[_i];
  79081. serializationObject.targets.push(target.serialize());
  79082. }
  79083. return serializationObject;
  79084. };
  79085. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  79086. var influenceCount = 0;
  79087. this._activeTargets.reset();
  79088. this._supportsNormals = true;
  79089. this._supportsTangents = true;
  79090. this._vertexCount = 0;
  79091. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  79092. var target = _a[_i];
  79093. this._activeTargets.push(target);
  79094. this._tempInfluences[influenceCount++] = target.influence;
  79095. var positions = target.getPositions();
  79096. if (positions) {
  79097. this._supportsNormals = this._supportsNormals && target.hasNormals;
  79098. this._supportsTangents = this._supportsTangents && target.hasTangents;
  79099. var vertexCount = positions.length / 3;
  79100. if (this._vertexCount === 0) {
  79101. this._vertexCount = vertexCount;
  79102. }
  79103. else if (this._vertexCount !== vertexCount) {
  79104. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  79105. return;
  79106. }
  79107. }
  79108. }
  79109. if (!this._influences || this._influences.length !== influenceCount) {
  79110. this._influences = new Float32Array(influenceCount);
  79111. }
  79112. for (var index = 0; index < influenceCount; index++) {
  79113. this._influences[index] = this._tempInfluences[index];
  79114. }
  79115. if (needUpdate && this._scene) {
  79116. // Flag meshes as dirty to resync with the active targets
  79117. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  79118. var mesh = _c[_b];
  79119. if (mesh.morphTargetManager === this) {
  79120. mesh._syncGeometryWithMorphTargetManager();
  79121. }
  79122. }
  79123. }
  79124. };
  79125. // Statics
  79126. MorphTargetManager.Parse = function (serializationObject, scene) {
  79127. var result = new MorphTargetManager(scene);
  79128. result._uniqueId = serializationObject.id;
  79129. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  79130. var targetData = _a[_i];
  79131. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  79132. }
  79133. return result;
  79134. };
  79135. return MorphTargetManager;
  79136. }());
  79137. BABYLON.MorphTargetManager = MorphTargetManager;
  79138. })(BABYLON || (BABYLON = {}));
  79139. //# sourceMappingURL=babylon.morphTargetManager.js.map
  79140. var BABYLON;
  79141. (function (BABYLON) {
  79142. var Octree = /** @class */ (function () {
  79143. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  79144. if (maxDepth === void 0) { maxDepth = 2; }
  79145. this.maxDepth = maxDepth;
  79146. this.dynamicContent = new Array();
  79147. this._maxBlockCapacity = maxBlockCapacity || 64;
  79148. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  79149. this._creationFunc = creationFunc;
  79150. }
  79151. // Methods
  79152. Octree.prototype.update = function (worldMin, worldMax, entries) {
  79153. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  79154. };
  79155. Octree.prototype.addMesh = function (entry) {
  79156. for (var index = 0; index < this.blocks.length; index++) {
  79157. var block = this.blocks[index];
  79158. block.addEntry(entry);
  79159. }
  79160. };
  79161. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  79162. this._selectionContent.reset();
  79163. for (var index = 0; index < this.blocks.length; index++) {
  79164. var block = this.blocks[index];
  79165. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  79166. }
  79167. if (allowDuplicate) {
  79168. this._selectionContent.concat(this.dynamicContent);
  79169. }
  79170. else {
  79171. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  79172. }
  79173. return this._selectionContent;
  79174. };
  79175. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  79176. this._selectionContent.reset();
  79177. for (var index = 0; index < this.blocks.length; index++) {
  79178. var block = this.blocks[index];
  79179. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  79180. }
  79181. if (allowDuplicate) {
  79182. this._selectionContent.concat(this.dynamicContent);
  79183. }
  79184. else {
  79185. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  79186. }
  79187. return this._selectionContent;
  79188. };
  79189. Octree.prototype.intersectsRay = function (ray) {
  79190. this._selectionContent.reset();
  79191. for (var index = 0; index < this.blocks.length; index++) {
  79192. var block = this.blocks[index];
  79193. block.intersectsRay(ray, this._selectionContent);
  79194. }
  79195. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  79196. return this._selectionContent;
  79197. };
  79198. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  79199. target.blocks = new Array();
  79200. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  79201. // Segmenting space
  79202. for (var x = 0; x < 2; x++) {
  79203. for (var y = 0; y < 2; y++) {
  79204. for (var z = 0; z < 2; z++) {
  79205. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  79206. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  79207. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  79208. block.addEntries(entries);
  79209. target.blocks.push(block);
  79210. }
  79211. }
  79212. }
  79213. };
  79214. Octree.CreationFuncForMeshes = function (entry, block) {
  79215. var boundingInfo = entry.getBoundingInfo();
  79216. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  79217. block.entries.push(entry);
  79218. }
  79219. };
  79220. Octree.CreationFuncForSubMeshes = function (entry, block) {
  79221. var boundingInfo = entry.getBoundingInfo();
  79222. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  79223. block.entries.push(entry);
  79224. }
  79225. };
  79226. return Octree;
  79227. }());
  79228. BABYLON.Octree = Octree;
  79229. })(BABYLON || (BABYLON = {}));
  79230. //# sourceMappingURL=babylon.octree.js.map
  79231. var BABYLON;
  79232. (function (BABYLON) {
  79233. var OctreeBlock = /** @class */ (function () {
  79234. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  79235. this.entries = new Array();
  79236. this._boundingVectors = new Array();
  79237. this._capacity = capacity;
  79238. this._depth = depth;
  79239. this._maxDepth = maxDepth;
  79240. this._creationFunc = creationFunc;
  79241. this._minPoint = minPoint;
  79242. this._maxPoint = maxPoint;
  79243. this._boundingVectors.push(minPoint.clone());
  79244. this._boundingVectors.push(maxPoint.clone());
  79245. this._boundingVectors.push(minPoint.clone());
  79246. this._boundingVectors[2].x = maxPoint.x;
  79247. this._boundingVectors.push(minPoint.clone());
  79248. this._boundingVectors[3].y = maxPoint.y;
  79249. this._boundingVectors.push(minPoint.clone());
  79250. this._boundingVectors[4].z = maxPoint.z;
  79251. this._boundingVectors.push(maxPoint.clone());
  79252. this._boundingVectors[5].z = minPoint.z;
  79253. this._boundingVectors.push(maxPoint.clone());
  79254. this._boundingVectors[6].x = minPoint.x;
  79255. this._boundingVectors.push(maxPoint.clone());
  79256. this._boundingVectors[7].y = minPoint.y;
  79257. }
  79258. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  79259. // Property
  79260. get: function () {
  79261. return this._capacity;
  79262. },
  79263. enumerable: true,
  79264. configurable: true
  79265. });
  79266. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  79267. get: function () {
  79268. return this._minPoint;
  79269. },
  79270. enumerable: true,
  79271. configurable: true
  79272. });
  79273. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  79274. get: function () {
  79275. return this._maxPoint;
  79276. },
  79277. enumerable: true,
  79278. configurable: true
  79279. });
  79280. // Methods
  79281. OctreeBlock.prototype.addEntry = function (entry) {
  79282. if (this.blocks) {
  79283. for (var index = 0; index < this.blocks.length; index++) {
  79284. var block = this.blocks[index];
  79285. block.addEntry(entry);
  79286. }
  79287. return;
  79288. }
  79289. this._creationFunc(entry, this);
  79290. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  79291. this.createInnerBlocks();
  79292. }
  79293. };
  79294. OctreeBlock.prototype.addEntries = function (entries) {
  79295. for (var index = 0; index < entries.length; index++) {
  79296. var mesh = entries[index];
  79297. this.addEntry(mesh);
  79298. }
  79299. };
  79300. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  79301. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  79302. if (this.blocks) {
  79303. for (var index = 0; index < this.blocks.length; index++) {
  79304. var block = this.blocks[index];
  79305. block.select(frustumPlanes, selection, allowDuplicate);
  79306. }
  79307. return;
  79308. }
  79309. if (allowDuplicate) {
  79310. selection.concat(this.entries);
  79311. }
  79312. else {
  79313. selection.concatWithNoDuplicate(this.entries);
  79314. }
  79315. }
  79316. };
  79317. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  79318. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  79319. if (this.blocks) {
  79320. for (var index = 0; index < this.blocks.length; index++) {
  79321. var block = this.blocks[index];
  79322. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  79323. }
  79324. return;
  79325. }
  79326. if (allowDuplicate) {
  79327. selection.concat(this.entries);
  79328. }
  79329. else {
  79330. selection.concatWithNoDuplicate(this.entries);
  79331. }
  79332. }
  79333. };
  79334. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  79335. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  79336. if (this.blocks) {
  79337. for (var index = 0; index < this.blocks.length; index++) {
  79338. var block = this.blocks[index];
  79339. block.intersectsRay(ray, selection);
  79340. }
  79341. return;
  79342. }
  79343. selection.concatWithNoDuplicate(this.entries);
  79344. }
  79345. };
  79346. OctreeBlock.prototype.createInnerBlocks = function () {
  79347. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  79348. };
  79349. return OctreeBlock;
  79350. }());
  79351. BABYLON.OctreeBlock = OctreeBlock;
  79352. })(BABYLON || (BABYLON = {}));
  79353. //# sourceMappingURL=babylon.octreeBlock.js.map
  79354. var BABYLON;
  79355. (function (BABYLON) {
  79356. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  79357. __extends(VRDistortionCorrectionPostProcess, _super);
  79358. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  79359. var _this = _super.call(this, name, "vrDistortionCorrection", [
  79360. 'LensCenter',
  79361. 'Scale',
  79362. 'ScaleIn',
  79363. 'HmdWarpParam'
  79364. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  79365. _this._isRightEye = isRightEye;
  79366. _this._distortionFactors = vrMetrics.distortionK;
  79367. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  79368. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  79369. _this.adaptScaleToCurrentViewport = true;
  79370. _this.onSizeChangedObservable.add(function () {
  79371. _this.aspectRatio = _this.width * .5 / _this.height;
  79372. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  79373. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  79374. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  79375. });
  79376. _this.onApplyObservable.add(function (effect) {
  79377. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  79378. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  79379. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  79380. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  79381. });
  79382. return _this;
  79383. }
  79384. return VRDistortionCorrectionPostProcess;
  79385. }(BABYLON.PostProcess));
  79386. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  79387. })(BABYLON || (BABYLON = {}));
  79388. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  79389. var BABYLON;
  79390. (function (BABYLON) {
  79391. var AnaglyphPostProcess = /** @class */ (function (_super) {
  79392. __extends(AnaglyphPostProcess, _super);
  79393. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  79394. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  79395. _this._passedProcess = rigCameras[0]._rigPostProcess;
  79396. _this.onApplyObservable.add(function (effect) {
  79397. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  79398. });
  79399. return _this;
  79400. }
  79401. return AnaglyphPostProcess;
  79402. }(BABYLON.PostProcess));
  79403. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  79404. })(BABYLON || (BABYLON = {}));
  79405. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  79406. var BABYLON;
  79407. (function (BABYLON) {
  79408. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  79409. __extends(StereoscopicInterlacePostProcess, _super);
  79410. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  79411. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  79412. _this._passedProcess = rigCameras[0]._rigPostProcess;
  79413. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  79414. _this.onSizeChangedObservable.add(function () {
  79415. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  79416. });
  79417. _this.onApplyObservable.add(function (effect) {
  79418. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  79419. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  79420. });
  79421. return _this;
  79422. }
  79423. return StereoscopicInterlacePostProcess;
  79424. }(BABYLON.PostProcess));
  79425. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  79426. })(BABYLON || (BABYLON = {}));
  79427. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  79428. var BABYLON;
  79429. (function (BABYLON) {
  79430. /**
  79431. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  79432. * Screen rotation is taken into account.
  79433. */
  79434. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  79435. function FreeCameraDeviceOrientationInput() {
  79436. var _this = this;
  79437. this._screenOrientationAngle = 0;
  79438. this._screenQuaternion = new BABYLON.Quaternion();
  79439. this._alpha = 0;
  79440. this._beta = 0;
  79441. this._gamma = 0;
  79442. this._orientationChanged = function () {
  79443. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  79444. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  79445. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  79446. };
  79447. this._deviceOrientation = function (evt) {
  79448. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  79449. _this._beta = evt.beta !== null ? evt.beta : 0;
  79450. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  79451. };
  79452. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  79453. this._orientationChanged();
  79454. }
  79455. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  79456. get: function () {
  79457. return this._camera;
  79458. },
  79459. set: function (camera) {
  79460. this._camera = camera;
  79461. if (this._camera != null && !this._camera.rotationQuaternion) {
  79462. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  79463. }
  79464. },
  79465. enumerable: true,
  79466. configurable: true
  79467. });
  79468. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  79469. window.addEventListener("orientationchange", this._orientationChanged);
  79470. window.addEventListener("deviceorientation", this._deviceOrientation);
  79471. //In certain cases, the attach control is called AFTER orientation was changed,
  79472. //So this is needed.
  79473. this._orientationChanged();
  79474. };
  79475. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  79476. window.removeEventListener("orientationchange", this._orientationChanged);
  79477. window.removeEventListener("deviceorientation", this._deviceOrientation);
  79478. };
  79479. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  79480. //if no device orientation provided, don't update the rotation.
  79481. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  79482. if (!this._alpha)
  79483. return;
  79484. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  79485. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  79486. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  79487. //Mirror on XY Plane
  79488. this._camera.rotationQuaternion.z *= -1;
  79489. this._camera.rotationQuaternion.w *= -1;
  79490. };
  79491. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  79492. return "FreeCameraDeviceOrientationInput";
  79493. };
  79494. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  79495. return "deviceOrientation";
  79496. };
  79497. return FreeCameraDeviceOrientationInput;
  79498. }());
  79499. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  79500. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  79501. })(BABYLON || (BABYLON = {}));
  79502. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  79503. var BABYLON;
  79504. (function (BABYLON) {
  79505. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  79506. function ArcRotateCameraVRDeviceOrientationInput() {
  79507. this.alphaCorrection = 1;
  79508. this.betaCorrection = 1;
  79509. this.gammaCorrection = 1;
  79510. this._alpha = 0;
  79511. this._gamma = 0;
  79512. this._dirty = false;
  79513. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  79514. }
  79515. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  79516. this.camera.attachControl(element, noPreventDefault);
  79517. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  79518. };
  79519. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  79520. if (evt.alpha !== null) {
  79521. this._alpha = +evt.alpha | 0;
  79522. }
  79523. if (evt.gamma !== null) {
  79524. this._gamma = +evt.gamma | 0;
  79525. }
  79526. this._dirty = true;
  79527. };
  79528. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  79529. if (this._dirty) {
  79530. this._dirty = false;
  79531. if (this._gamma < 0) {
  79532. this._gamma = 180 + this._gamma;
  79533. }
  79534. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  79535. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  79536. }
  79537. };
  79538. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  79539. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  79540. };
  79541. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  79542. return "ArcRotateCameraVRDeviceOrientationInput";
  79543. };
  79544. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  79545. return "VRDeviceOrientation";
  79546. };
  79547. return ArcRotateCameraVRDeviceOrientationInput;
  79548. }());
  79549. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  79550. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  79551. })(BABYLON || (BABYLON = {}));
  79552. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  79553. var BABYLON;
  79554. (function (BABYLON) {
  79555. var VRCameraMetrics = /** @class */ (function () {
  79556. function VRCameraMetrics() {
  79557. this.compensateDistortion = true;
  79558. }
  79559. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  79560. get: function () {
  79561. return this.hResolution / (2 * this.vResolution);
  79562. },
  79563. enumerable: true,
  79564. configurable: true
  79565. });
  79566. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  79567. get: function () {
  79568. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  79569. },
  79570. enumerable: true,
  79571. configurable: true
  79572. });
  79573. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  79574. get: function () {
  79575. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  79576. var h = (4 * meters) / this.hScreenSize;
  79577. return BABYLON.Matrix.Translation(h, 0, 0);
  79578. },
  79579. enumerable: true,
  79580. configurable: true
  79581. });
  79582. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  79583. get: function () {
  79584. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  79585. var h = (4 * meters) / this.hScreenSize;
  79586. return BABYLON.Matrix.Translation(-h, 0, 0);
  79587. },
  79588. enumerable: true,
  79589. configurable: true
  79590. });
  79591. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  79592. get: function () {
  79593. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  79594. },
  79595. enumerable: true,
  79596. configurable: true
  79597. });
  79598. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  79599. get: function () {
  79600. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  79601. },
  79602. enumerable: true,
  79603. configurable: true
  79604. });
  79605. VRCameraMetrics.GetDefault = function () {
  79606. var result = new VRCameraMetrics();
  79607. result.hResolution = 1280;
  79608. result.vResolution = 800;
  79609. result.hScreenSize = 0.149759993;
  79610. result.vScreenSize = 0.0935999975;
  79611. result.vScreenCenter = 0.0467999987;
  79612. result.eyeToScreenDistance = 0.0410000011;
  79613. result.lensSeparationDistance = 0.0635000020;
  79614. result.interpupillaryDistance = 0.0640000030;
  79615. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  79616. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  79617. result.postProcessScaleFactor = 1.714605507808412;
  79618. result.lensCenterOffset = 0.151976421;
  79619. return result;
  79620. };
  79621. return VRCameraMetrics;
  79622. }());
  79623. BABYLON.VRCameraMetrics = VRCameraMetrics;
  79624. })(BABYLON || (BABYLON = {}));
  79625. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  79626. var BABYLON;
  79627. (function (BABYLON) {
  79628. /**
  79629. * This represents a WebVR camera.
  79630. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  79631. * @example http://doc.babylonjs.com/how_to/webvr_camera
  79632. */
  79633. var WebVRFreeCamera = /** @class */ (function (_super) {
  79634. __extends(WebVRFreeCamera, _super);
  79635. /**
  79636. * Instantiates a WebVRFreeCamera.
  79637. * @param name The name of the WebVRFreeCamera
  79638. * @param position The starting anchor position for the camera
  79639. * @param scene The scene the camera belongs to
  79640. * @param webVROptions a set of customizable options for the webVRCamera
  79641. */
  79642. function WebVRFreeCamera(name, position, scene, webVROptions) {
  79643. if (webVROptions === void 0) { webVROptions = {}; }
  79644. var _this = _super.call(this, name, position, scene) || this;
  79645. _this.webVROptions = webVROptions;
  79646. /**
  79647. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  79648. */
  79649. _this._vrDevice = null;
  79650. /**
  79651. * The rawPose of the vrDevice.
  79652. */
  79653. _this.rawPose = null;
  79654. _this._specsVersion = "1.1";
  79655. _this._attached = false;
  79656. _this._descendants = [];
  79657. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  79658. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  79659. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  79660. _this._standingMatrix = null;
  79661. /**
  79662. * Represents device position in babylon space.
  79663. */
  79664. _this.devicePosition = BABYLON.Vector3.Zero();
  79665. /**
  79666. * Represents device rotation in babylon space.
  79667. */
  79668. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  79669. /**
  79670. * The scale of the device to be used when translating from device space to babylon space.
  79671. */
  79672. _this.deviceScaleFactor = 1;
  79673. _this._deviceToWorld = BABYLON.Matrix.Identity();
  79674. _this._worldToDevice = BABYLON.Matrix.Identity();
  79675. /**
  79676. * References to the webVR controllers for the vrDevice.
  79677. */
  79678. _this.controllers = [];
  79679. /**
  79680. * Emits an event when a controller is attached.
  79681. */
  79682. _this.onControllersAttachedObservable = new BABYLON.Observable();
  79683. /**
  79684. * Emits an event when a controller's mesh has been loaded;
  79685. */
  79686. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  79687. /**
  79688. * If the rig cameras be used as parent instead of this camera.
  79689. */
  79690. _this.rigParenting = true;
  79691. _this._defaultHeight = undefined;
  79692. _this._workingVector = BABYLON.Vector3.Zero();
  79693. _this._oneVector = BABYLON.Vector3.One();
  79694. _this._workingMatrix = BABYLON.Matrix.Identity();
  79695. _this._cache.position = BABYLON.Vector3.Zero();
  79696. if (webVROptions.defaultHeight) {
  79697. _this._defaultHeight = webVROptions.defaultHeight;
  79698. _this.position.y = _this._defaultHeight;
  79699. }
  79700. _this.minZ = 0.1;
  79701. //legacy support - the compensation boolean was removed.
  79702. if (arguments.length === 5) {
  79703. _this.webVROptions = arguments[4];
  79704. }
  79705. // default webVR options
  79706. if (_this.webVROptions.trackPosition == undefined) {
  79707. _this.webVROptions.trackPosition = true;
  79708. }
  79709. if (_this.webVROptions.controllerMeshes == undefined) {
  79710. _this.webVROptions.controllerMeshes = true;
  79711. }
  79712. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  79713. _this.webVROptions.defaultLightingOnControllers = true;
  79714. }
  79715. _this.rotationQuaternion = new BABYLON.Quaternion();
  79716. if (_this.webVROptions && _this.webVROptions.positionScale) {
  79717. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  79718. }
  79719. //enable VR
  79720. var engine = _this.getEngine();
  79721. _this._onVREnabled = function (success) { if (success) {
  79722. _this.initControllers();
  79723. } };
  79724. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  79725. engine.initWebVR().add(function (event) {
  79726. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  79727. return;
  79728. }
  79729. _this._vrDevice = event.vrDisplay;
  79730. //reset the rig parameters.
  79731. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  79732. if (_this._attached) {
  79733. _this.getEngine().enableVR();
  79734. }
  79735. });
  79736. if (typeof (VRFrameData) !== "undefined")
  79737. _this._frameData = new VRFrameData();
  79738. /**
  79739. * The idea behind the following lines:
  79740. * objects that have the camera as parent should actually have the rig cameras as a parent.
  79741. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  79742. * the second will not show it correctly.
  79743. *
  79744. * To solve this - each object that has the camera as parent will be added to a protected array.
  79745. * When the rig camera renders, it will take this array and set all of those to be its children.
  79746. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  79747. * Amazing!
  79748. */
  79749. scene.onBeforeCameraRenderObservable.add(function (camera) {
  79750. if (camera.parent === _this && _this.rigParenting) {
  79751. _this._descendants = _this.getDescendants(true, function (n) {
  79752. // don't take the cameras or the controllers!
  79753. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  79754. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  79755. return !isController && !isRigCamera;
  79756. });
  79757. _this._descendants.forEach(function (node) {
  79758. node.parent = camera;
  79759. });
  79760. }
  79761. });
  79762. scene.onAfterCameraRenderObservable.add(function (camera) {
  79763. if (camera.parent === _this && _this.rigParenting) {
  79764. _this._descendants.forEach(function (node) {
  79765. node.parent = _this;
  79766. });
  79767. }
  79768. });
  79769. return _this;
  79770. }
  79771. /**
  79772. * Gets the device distance from the ground in meters.
  79773. * @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.
  79774. */
  79775. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  79776. if (this._standingMatrix) {
  79777. // Add standing matrix offset to get real offset from ground in room
  79778. this._standingMatrix.getTranslationToRef(this._workingVector);
  79779. return this._deviceRoomPosition.y + this._workingVector.y;
  79780. }
  79781. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  79782. return this._defaultHeight || 0;
  79783. };
  79784. /**
  79785. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  79786. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  79787. */
  79788. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  79789. var _this = this;
  79790. if (callback === void 0) { callback = function (bool) { }; }
  79791. // Use standing matrix if available
  79792. this.getEngine().initWebVRAsync().then(function (result) {
  79793. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  79794. callback(false);
  79795. }
  79796. else {
  79797. _this._standingMatrix = new BABYLON.Matrix();
  79798. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  79799. if (!_this.getScene().useRightHandedSystem) {
  79800. [2, 6, 8, 9, 14].forEach(function (num) {
  79801. if (_this._standingMatrix) {
  79802. _this._standingMatrix.m[num] *= -1;
  79803. }
  79804. });
  79805. }
  79806. callback(true);
  79807. }
  79808. });
  79809. };
  79810. /**
  79811. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  79812. * @returns A promise with a boolean set to if the standing matrix is supported.
  79813. */
  79814. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  79815. var _this = this;
  79816. return new Promise(function (res, rej) {
  79817. _this.useStandingMatrix(function (supported) {
  79818. res(supported);
  79819. });
  79820. });
  79821. };
  79822. /**
  79823. * Disposes the camera
  79824. */
  79825. WebVRFreeCamera.prototype.dispose = function () {
  79826. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  79827. _super.prototype.dispose.call(this);
  79828. };
  79829. /**
  79830. * Gets a vrController by name.
  79831. * @param name The name of the controller to retreive
  79832. * @returns the controller matching the name specified or null if not found
  79833. */
  79834. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  79835. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  79836. var gp = _a[_i];
  79837. if (gp.hand === name) {
  79838. return gp;
  79839. }
  79840. }
  79841. return null;
  79842. };
  79843. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  79844. /**
  79845. * The controller corrisponding to the users left hand.
  79846. */
  79847. get: function () {
  79848. if (!this._leftController) {
  79849. this._leftController = this.getControllerByName("left");
  79850. }
  79851. return this._leftController;
  79852. },
  79853. enumerable: true,
  79854. configurable: true
  79855. });
  79856. ;
  79857. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  79858. /**
  79859. * The controller corrisponding to the users right hand.
  79860. */
  79861. get: function () {
  79862. if (!this._rightController) {
  79863. this._rightController = this.getControllerByName("right");
  79864. }
  79865. return this._rightController;
  79866. },
  79867. enumerable: true,
  79868. configurable: true
  79869. });
  79870. ;
  79871. /**
  79872. * Casts a ray forward from the vrCamera's gaze.
  79873. * @param length Length of the ray (default: 100)
  79874. * @returns the ray corrisponding to the gaze
  79875. */
  79876. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  79877. if (length === void 0) { length = 100; }
  79878. if (this.leftCamera) {
  79879. // Use left eye to avoid computation to compute center on every call
  79880. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  79881. }
  79882. else {
  79883. return _super.prototype.getForwardRay.call(this, length);
  79884. }
  79885. };
  79886. /**
  79887. * Updates the camera based on device's frame data
  79888. */
  79889. WebVRFreeCamera.prototype._checkInputs = function () {
  79890. if (this._vrDevice && this._vrDevice.isPresenting) {
  79891. this._vrDevice.getFrameData(this._frameData);
  79892. this.updateFromDevice(this._frameData.pose);
  79893. }
  79894. _super.prototype._checkInputs.call(this);
  79895. };
  79896. /**
  79897. * Updates the poseControlled values based on the input device pose.
  79898. * @param poseData Pose coming from the device
  79899. */
  79900. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  79901. if (poseData && poseData.orientation) {
  79902. this.rawPose = poseData;
  79903. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  79904. if (this.getScene().useRightHandedSystem) {
  79905. this._deviceRoomRotationQuaternion.z *= -1;
  79906. this._deviceRoomRotationQuaternion.w *= -1;
  79907. }
  79908. if (this.webVROptions.trackPosition && this.rawPose.position) {
  79909. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  79910. if (this.getScene().useRightHandedSystem) {
  79911. this._deviceRoomPosition.z *= -1;
  79912. }
  79913. }
  79914. }
  79915. };
  79916. /**
  79917. * WebVR's attach control will start broadcasting frames to the device.
  79918. * Note that in certain browsers (chrome for example) this function must be called
  79919. * within a user-interaction callback. Example:
  79920. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  79921. *
  79922. * @param element html element to attach the vrDevice to
  79923. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  79924. */
  79925. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  79926. _super.prototype.attachControl.call(this, element, noPreventDefault);
  79927. this._attached = true;
  79928. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  79929. if (this._vrDevice) {
  79930. this.getEngine().enableVR();
  79931. }
  79932. };
  79933. /**
  79934. * Detaches the camera from the html element and disables VR
  79935. *
  79936. * @param element html element to detach from
  79937. */
  79938. WebVRFreeCamera.prototype.detachControl = function (element) {
  79939. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  79940. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  79941. _super.prototype.detachControl.call(this, element);
  79942. this._attached = false;
  79943. this.getEngine().disableVR();
  79944. };
  79945. /**
  79946. * @returns the name of this class
  79947. */
  79948. WebVRFreeCamera.prototype.getClassName = function () {
  79949. return "WebVRFreeCamera";
  79950. };
  79951. /**
  79952. * Calls resetPose on the vrDisplay
  79953. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  79954. */
  79955. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  79956. //uses the vrDisplay's "resetPose()".
  79957. //pitch and roll won't be affected.
  79958. this._vrDevice.resetPose();
  79959. };
  79960. /**
  79961. * Updates the rig cameras (left and right eye)
  79962. */
  79963. WebVRFreeCamera.prototype._updateRigCameras = function () {
  79964. var camLeft = this._rigCameras[0];
  79965. var camRight = this._rigCameras[1];
  79966. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  79967. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  79968. camLeft.position.copyFrom(this._deviceRoomPosition);
  79969. camRight.position.copyFrom(this._deviceRoomPosition);
  79970. };
  79971. /**
  79972. * Updates the cached values of the camera
  79973. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  79974. */
  79975. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  79976. var _this = this;
  79977. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  79978. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  79979. if (!this.updateCacheCalled) {
  79980. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  79981. this.updateCacheCalled = true;
  79982. this.update();
  79983. }
  79984. // Set working vector to the device position in room space rotated by the new rotation
  79985. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  79986. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  79987. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  79988. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  79989. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  79990. // Add translation from anchor position
  79991. this._deviceToWorld.getTranslationToRef(this._workingVector);
  79992. this._workingVector.addInPlace(this.position);
  79993. this._workingVector.subtractInPlace(this._cache.position);
  79994. this._deviceToWorld.setTranslation(this._workingVector);
  79995. // Set an inverted matrix to be used when updating the camera
  79996. this._deviceToWorld.invertToRef(this._worldToDevice);
  79997. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  79998. this.controllers.forEach(function (controller) {
  79999. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  80000. controller.update();
  80001. });
  80002. }
  80003. if (!ignoreParentClass) {
  80004. _super.prototype._updateCache.call(this);
  80005. }
  80006. this.updateCacheCalled = false;
  80007. };
  80008. /**
  80009. * Updates the current device position and rotation in the babylon world
  80010. */
  80011. WebVRFreeCamera.prototype.update = function () {
  80012. // Get current device position in babylon world
  80013. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  80014. // Get current device rotation in babylon world
  80015. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  80016. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  80017. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  80018. _super.prototype.update.call(this);
  80019. };
  80020. /**
  80021. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  80022. * @returns an identity matrix
  80023. */
  80024. WebVRFreeCamera.prototype._getViewMatrix = function () {
  80025. return BABYLON.Matrix.Identity();
  80026. };
  80027. /**
  80028. * This function is called by the two RIG cameras.
  80029. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  80030. */
  80031. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  80032. var _this = this;
  80033. // Update the parent camera prior to using a child camera to avoid desynchronization
  80034. var parentCamera = this._cameraRigParams["parentCamera"];
  80035. parentCamera._updateCache();
  80036. //WebVR 1.1
  80037. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  80038. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  80039. if (!this.getScene().useRightHandedSystem) {
  80040. [2, 6, 8, 9, 14].forEach(function (num) {
  80041. _this._webvrViewMatrix.m[num] *= -1;
  80042. });
  80043. }
  80044. // update the camera rotation matrix
  80045. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  80046. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  80047. // Computing target and final matrix
  80048. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  80049. // should the view matrix be updated with scale and position offset?
  80050. if (parentCamera.deviceScaleFactor !== 1) {
  80051. this._webvrViewMatrix.invert();
  80052. // scale the position, if set
  80053. if (parentCamera.deviceScaleFactor) {
  80054. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  80055. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  80056. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  80057. }
  80058. this._webvrViewMatrix.invert();
  80059. }
  80060. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  80061. return this._webvrViewMatrix;
  80062. };
  80063. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  80064. var _this = this;
  80065. var parentCamera = this.parent;
  80066. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  80067. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  80068. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  80069. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  80070. //babylon compatible matrix
  80071. if (!this.getScene().useRightHandedSystem) {
  80072. [8, 9, 10, 11].forEach(function (num) {
  80073. _this._projectionMatrix.m[num] *= -1;
  80074. });
  80075. }
  80076. return this._projectionMatrix;
  80077. };
  80078. /**
  80079. * Initializes the controllers and their meshes
  80080. */
  80081. WebVRFreeCamera.prototype.initControllers = function () {
  80082. var _this = this;
  80083. this.controllers = [];
  80084. var manager = this.getScene().gamepadManager;
  80085. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  80086. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  80087. var webVrController = gamepad;
  80088. if (webVrController.defaultModel) {
  80089. webVrController.defaultModel.setEnabled(false);
  80090. }
  80091. if (webVrController.hand === "right") {
  80092. _this._rightController = null;
  80093. }
  80094. if (webVrController.hand === "left") {
  80095. _this._leftController = null;
  80096. }
  80097. var controllerIndex = _this.controllers.indexOf(webVrController);
  80098. if (controllerIndex !== -1) {
  80099. _this.controllers.splice(controllerIndex, 1);
  80100. }
  80101. }
  80102. });
  80103. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  80104. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  80105. var webVrController_1 = gamepad;
  80106. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  80107. if (_this.webVROptions.controllerMeshes) {
  80108. if (webVrController_1.defaultModel) {
  80109. webVrController_1.defaultModel.setEnabled(true);
  80110. }
  80111. else {
  80112. // Load the meshes
  80113. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  80114. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  80115. if (_this.webVROptions.defaultLightingOnControllers) {
  80116. if (!_this._lightOnControllers) {
  80117. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  80118. }
  80119. var activateLightOnSubMeshes_1 = function (mesh, light) {
  80120. var children = mesh.getChildren();
  80121. if (children.length !== 0) {
  80122. children.forEach(function (mesh) {
  80123. light.includedOnlyMeshes.push(mesh);
  80124. activateLightOnSubMeshes_1(mesh, light);
  80125. });
  80126. }
  80127. };
  80128. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  80129. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  80130. }
  80131. });
  80132. }
  80133. }
  80134. webVrController_1.attachToPoseControlledCamera(_this);
  80135. // since this is async - sanity check. Is the controller already stored?
  80136. if (_this.controllers.indexOf(webVrController_1) === -1) {
  80137. //add to the controllers array
  80138. _this.controllers.push(webVrController_1);
  80139. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  80140. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  80141. // So we're overriding setting left & right manually to be sure
  80142. var firstViveWandDetected = false;
  80143. for (var i = 0; i < _this.controllers.length; i++) {
  80144. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  80145. if (!firstViveWandDetected) {
  80146. firstViveWandDetected = true;
  80147. _this.controllers[i].hand = "left";
  80148. }
  80149. else {
  80150. _this.controllers[i].hand = "right";
  80151. }
  80152. }
  80153. }
  80154. //did we find enough controllers? Great! let the developer know.
  80155. if (_this.controllers.length >= 2) {
  80156. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  80157. }
  80158. }
  80159. }
  80160. });
  80161. };
  80162. return WebVRFreeCamera;
  80163. }(BABYLON.FreeCamera));
  80164. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  80165. })(BABYLON || (BABYLON = {}));
  80166. //# sourceMappingURL=babylon.webVRCamera.js.map
  80167. var BABYLON;
  80168. (function (BABYLON) {
  80169. // We're mainly based on the logic defined into the FreeCamera code
  80170. /**
  80171. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  80172. * being tilted forward or back and left or right.
  80173. */
  80174. var DeviceOrientationCamera = /** @class */ (function (_super) {
  80175. __extends(DeviceOrientationCamera, _super);
  80176. /**
  80177. * Creates a new device orientation camera. @see DeviceOrientationCamera
  80178. * @param name The name of the camera
  80179. * @param position The start position camera
  80180. * @param scene The scene the camera belongs to
  80181. */
  80182. function DeviceOrientationCamera(name, position, scene) {
  80183. var _this = _super.call(this, name, position, scene) || this;
  80184. _this._quaternionCache = new BABYLON.Quaternion();
  80185. _this.inputs.addDeviceOrientation();
  80186. return _this;
  80187. }
  80188. /**
  80189. * Gets the current instance class name ("DeviceOrientationCamera").
  80190. * This helps avoiding instanceof at run time.
  80191. * @returns the class name
  80192. */
  80193. DeviceOrientationCamera.prototype.getClassName = function () {
  80194. return "DeviceOrientationCamera";
  80195. };
  80196. /**
  80197. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  80198. */
  80199. DeviceOrientationCamera.prototype._checkInputs = function () {
  80200. _super.prototype._checkInputs.call(this);
  80201. this._quaternionCache.copyFrom(this.rotationQuaternion);
  80202. if (this._initialQuaternion) {
  80203. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  80204. }
  80205. };
  80206. /**
  80207. * Reset the camera to its default orientation on the specified axis only.
  80208. * @param axis The axis to reset
  80209. */
  80210. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  80211. var _this = this;
  80212. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  80213. //can only work if this camera has a rotation quaternion already.
  80214. if (!this.rotationQuaternion)
  80215. return;
  80216. if (!this._initialQuaternion) {
  80217. this._initialQuaternion = new BABYLON.Quaternion();
  80218. }
  80219. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  80220. ['x', 'y', 'z'].forEach(function (axisName) {
  80221. if (!axis[axisName]) {
  80222. _this._initialQuaternion[axisName] = 0;
  80223. }
  80224. else {
  80225. _this._initialQuaternion[axisName] *= -1;
  80226. }
  80227. });
  80228. this._initialQuaternion.normalize();
  80229. //force rotation update
  80230. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  80231. };
  80232. return DeviceOrientationCamera;
  80233. }(BABYLON.FreeCamera));
  80234. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  80235. })(BABYLON || (BABYLON = {}));
  80236. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  80237. var BABYLON;
  80238. (function (BABYLON) {
  80239. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  80240. __extends(VRDeviceOrientationFreeCamera, _super);
  80241. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  80242. if (compensateDistortion === void 0) { compensateDistortion = true; }
  80243. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  80244. var _this = _super.call(this, name, position, scene) || this;
  80245. vrCameraMetrics.compensateDistortion = compensateDistortion;
  80246. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  80247. return _this;
  80248. }
  80249. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  80250. return "VRDeviceOrientationFreeCamera";
  80251. };
  80252. return VRDeviceOrientationFreeCamera;
  80253. }(BABYLON.DeviceOrientationCamera));
  80254. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  80255. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  80256. __extends(VRDeviceOrientationGamepadCamera, _super);
  80257. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  80258. if (compensateDistortion === void 0) { compensateDistortion = true; }
  80259. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  80260. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  80261. _this.inputs.addGamepad();
  80262. return _this;
  80263. }
  80264. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  80265. return "VRDeviceOrientationGamepadCamera";
  80266. };
  80267. return VRDeviceOrientationGamepadCamera;
  80268. }(VRDeviceOrientationFreeCamera));
  80269. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  80270. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  80271. __extends(VRDeviceOrientationArcRotateCamera, _super);
  80272. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  80273. if (compensateDistortion === void 0) { compensateDistortion = true; }
  80274. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  80275. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  80276. vrCameraMetrics.compensateDistortion = compensateDistortion;
  80277. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  80278. _this.inputs.addVRDeviceOrientation();
  80279. return _this;
  80280. }
  80281. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  80282. return "VRDeviceOrientationArcRotateCamera";
  80283. };
  80284. return VRDeviceOrientationArcRotateCamera;
  80285. }(BABYLON.ArcRotateCamera));
  80286. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  80287. })(BABYLON || (BABYLON = {}));
  80288. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  80289. var BABYLON;
  80290. (function (BABYLON) {
  80291. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  80292. __extends(AnaglyphFreeCamera, _super);
  80293. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  80294. var _this = _super.call(this, name, position, scene) || this;
  80295. _this.interaxialDistance = interaxialDistance;
  80296. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80297. return _this;
  80298. }
  80299. AnaglyphFreeCamera.prototype.getClassName = function () {
  80300. return "AnaglyphFreeCamera";
  80301. };
  80302. return AnaglyphFreeCamera;
  80303. }(BABYLON.FreeCamera));
  80304. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  80305. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  80306. __extends(AnaglyphArcRotateCamera, _super);
  80307. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  80308. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  80309. _this.interaxialDistance = interaxialDistance;
  80310. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80311. return _this;
  80312. }
  80313. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  80314. return "AnaglyphArcRotateCamera";
  80315. };
  80316. return AnaglyphArcRotateCamera;
  80317. }(BABYLON.ArcRotateCamera));
  80318. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  80319. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  80320. __extends(AnaglyphGamepadCamera, _super);
  80321. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  80322. var _this = _super.call(this, name, position, scene) || this;
  80323. _this.interaxialDistance = interaxialDistance;
  80324. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80325. return _this;
  80326. }
  80327. AnaglyphGamepadCamera.prototype.getClassName = function () {
  80328. return "AnaglyphGamepadCamera";
  80329. };
  80330. return AnaglyphGamepadCamera;
  80331. }(BABYLON.GamepadCamera));
  80332. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  80333. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  80334. __extends(AnaglyphUniversalCamera, _super);
  80335. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  80336. var _this = _super.call(this, name, position, scene) || this;
  80337. _this.interaxialDistance = interaxialDistance;
  80338. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80339. return _this;
  80340. }
  80341. AnaglyphUniversalCamera.prototype.getClassName = function () {
  80342. return "AnaglyphUniversalCamera";
  80343. };
  80344. return AnaglyphUniversalCamera;
  80345. }(BABYLON.UniversalCamera));
  80346. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  80347. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  80348. __extends(StereoscopicFreeCamera, _super);
  80349. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  80350. var _this = _super.call(this, name, position, scene) || this;
  80351. _this.interaxialDistance = interaxialDistance;
  80352. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80353. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80354. return _this;
  80355. }
  80356. StereoscopicFreeCamera.prototype.getClassName = function () {
  80357. return "StereoscopicFreeCamera";
  80358. };
  80359. return StereoscopicFreeCamera;
  80360. }(BABYLON.FreeCamera));
  80361. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  80362. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  80363. __extends(StereoscopicArcRotateCamera, _super);
  80364. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  80365. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  80366. _this.interaxialDistance = interaxialDistance;
  80367. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80368. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80369. return _this;
  80370. }
  80371. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  80372. return "StereoscopicArcRotateCamera";
  80373. };
  80374. return StereoscopicArcRotateCamera;
  80375. }(BABYLON.ArcRotateCamera));
  80376. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  80377. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  80378. __extends(StereoscopicGamepadCamera, _super);
  80379. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  80380. var _this = _super.call(this, name, position, scene) || this;
  80381. _this.interaxialDistance = interaxialDistance;
  80382. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80383. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80384. return _this;
  80385. }
  80386. StereoscopicGamepadCamera.prototype.getClassName = function () {
  80387. return "StereoscopicGamepadCamera";
  80388. };
  80389. return StereoscopicGamepadCamera;
  80390. }(BABYLON.GamepadCamera));
  80391. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  80392. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  80393. __extends(StereoscopicUniversalCamera, _super);
  80394. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  80395. var _this = _super.call(this, name, position, scene) || this;
  80396. _this.interaxialDistance = interaxialDistance;
  80397. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80398. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80399. return _this;
  80400. }
  80401. StereoscopicUniversalCamera.prototype.getClassName = function () {
  80402. return "StereoscopicUniversalCamera";
  80403. };
  80404. return StereoscopicUniversalCamera;
  80405. }(BABYLON.UniversalCamera));
  80406. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  80407. })(BABYLON || (BABYLON = {}));
  80408. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  80409. var BABYLON;
  80410. (function (BABYLON) {
  80411. var VRExperienceHelperGazer = /** @class */ (function () {
  80412. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  80413. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  80414. this.scene = scene;
  80415. this._pointerDownOnMeshAsked = false;
  80416. this._isActionableMesh = false;
  80417. this._teleportationRequestInitiated = false;
  80418. this._teleportationBackRequestInitiated = false;
  80419. this._dpadPressed = true;
  80420. this._activePointer = false;
  80421. this._id = VRExperienceHelperGazer._idCounter++;
  80422. // Gaze tracker
  80423. if (!gazeTrackerToClone) {
  80424. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  80425. this._gazeTracker.bakeCurrentTransformIntoVertices();
  80426. this._gazeTracker.isPickable = false;
  80427. this._gazeTracker.isVisible = false;
  80428. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  80429. targetMat.specularColor = BABYLON.Color3.Black();
  80430. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  80431. targetMat.backFaceCulling = false;
  80432. this._gazeTracker.material = targetMat;
  80433. }
  80434. else {
  80435. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  80436. }
  80437. }
  80438. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  80439. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  80440. };
  80441. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  80442. this._pointerDownOnMeshAsked = true;
  80443. if (this._currentMeshSelected && this._currentHit) {
  80444. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  80445. }
  80446. };
  80447. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  80448. if (this._currentMeshSelected && this._currentHit) {
  80449. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  80450. }
  80451. this._pointerDownOnMeshAsked = false;
  80452. };
  80453. VRExperienceHelperGazer.prototype._activatePointer = function () {
  80454. this._activePointer = true;
  80455. };
  80456. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  80457. this._activePointer = false;
  80458. };
  80459. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  80460. };
  80461. VRExperienceHelperGazer.prototype.dispose = function () {
  80462. this._interactionsEnabled = false;
  80463. this._teleportationEnabled = false;
  80464. };
  80465. VRExperienceHelperGazer._idCounter = 0;
  80466. return VRExperienceHelperGazer;
  80467. }());
  80468. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  80469. __extends(VRExperienceHelperControllerGazer, _super);
  80470. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  80471. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  80472. _this.webVRController = webVRController;
  80473. // Laser pointer
  80474. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  80475. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  80476. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  80477. laserPointerMaterial.alpha = 0.6;
  80478. _this._laserPointer.material = laserPointerMaterial;
  80479. _this._laserPointer.rotation.x = Math.PI / 2;
  80480. _this._laserPointer.position.z = -0.5;
  80481. _this._laserPointer.isVisible = false;
  80482. _this._laserPointer.parent = webVRController.mesh;
  80483. return _this;
  80484. }
  80485. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  80486. return this.webVRController.getForwardRay(length);
  80487. };
  80488. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  80489. _super.prototype._activatePointer.call(this);
  80490. this._laserPointer.isVisible = true;
  80491. };
  80492. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  80493. _super.prototype._deactivatePointer.call(this);
  80494. this._laserPointer.isVisible = false;
  80495. };
  80496. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  80497. this._laserPointer.material.emissiveColor = color;
  80498. };
  80499. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  80500. this._laserPointer.parent = mesh;
  80501. };
  80502. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  80503. this._laserPointer.scaling.y = distance;
  80504. this._laserPointer.position.z = -distance / 2;
  80505. };
  80506. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  80507. _super.prototype.dispose.call(this);
  80508. this._laserPointer.dispose();
  80509. };
  80510. return VRExperienceHelperControllerGazer;
  80511. }(VRExperienceHelperGazer));
  80512. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  80513. __extends(VRExperienceHelperCameraGazer, _super);
  80514. function VRExperienceHelperCameraGazer(getCamera, scene) {
  80515. var _this = _super.call(this, scene) || this;
  80516. _this.getCamera = getCamera;
  80517. return _this;
  80518. }
  80519. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  80520. var camera = this.getCamera();
  80521. if (camera) {
  80522. return camera.getForwardRay(length);
  80523. }
  80524. else {
  80525. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  80526. }
  80527. };
  80528. return VRExperienceHelperCameraGazer;
  80529. }(VRExperienceHelperGazer));
  80530. /**
  80531. * Helps to quickly add VR support to an existing scene.
  80532. * See http://doc.babylonjs.com/how_to/webvr_helper
  80533. */
  80534. var VRExperienceHelper = /** @class */ (function () {
  80535. /**
  80536. * Instantiates a VRExperienceHelper.
  80537. * Helps to quickly add VR support to an existing scene.
  80538. * @param scene The scene the VRExperienceHelper belongs to.
  80539. * @param webVROptions Options to modify the vr experience helper's behavior.
  80540. */
  80541. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  80542. if (webVROptions === void 0) { webVROptions = {}; }
  80543. var _this = this;
  80544. this.webVROptions = webVROptions;
  80545. // Can the system support WebVR, even if a headset isn't plugged in?
  80546. this._webVRsupported = false;
  80547. // If WebVR is supported, is a headset plugged in and are we ready to present?
  80548. this._webVRready = false;
  80549. // Are we waiting for the requestPresent callback to complete?
  80550. this._webVRrequesting = false;
  80551. // Are we presenting to the headset right now?
  80552. this._webVRpresenting = false;
  80553. // Are we presenting in the fullscreen fallback?
  80554. this._fullscreenVRpresenting = false;
  80555. /**
  80556. * Observable raised when entering VR.
  80557. */
  80558. this.onEnteringVRObservable = new BABYLON.Observable();
  80559. /**
  80560. * Observable raised when exiting VR.
  80561. */
  80562. this.onExitingVRObservable = new BABYLON.Observable();
  80563. /**
  80564. * Observable raised when controller mesh is loaded.
  80565. */
  80566. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  80567. this._useCustomVRButton = false;
  80568. this._teleportationRequested = false;
  80569. this._teleportActive = false;
  80570. this._floorMeshesCollection = [];
  80571. this._rotationAllowed = true;
  80572. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  80573. this._rotationRightAsked = false;
  80574. this._rotationLeftAsked = false;
  80575. this._isDefaultTeleportationTarget = true;
  80576. this._teleportationFillColor = "#444444";
  80577. this._teleportationBorderColor = "#FFFFFF";
  80578. this._rotationAngle = 0;
  80579. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  80580. this._padSensibilityUp = 0.65;
  80581. this._padSensibilityDown = 0.35;
  80582. this.leftController = null;
  80583. this.rightController = null;
  80584. /**
  80585. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  80586. */
  80587. this.onNewMeshSelected = new BABYLON.Observable();
  80588. /**
  80589. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  80590. */
  80591. this.onNewMeshPicked = new BABYLON.Observable();
  80592. /**
  80593. * Observable raised before camera teleportation
  80594. */
  80595. this.onBeforeCameraTeleport = new BABYLON.Observable();
  80596. /**
  80597. * Observable raised after camera teleportation
  80598. */
  80599. this.onAfterCameraTeleport = new BABYLON.Observable();
  80600. /**
  80601. * Observable raised when current selected mesh gets unselected
  80602. */
  80603. this.onSelectedMeshUnselected = new BABYLON.Observable();
  80604. /**
  80605. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  80606. */
  80607. this.teleportationEnabled = true;
  80608. this._teleportationInitialized = false;
  80609. this._interactionsEnabled = false;
  80610. this._interactionsRequested = false;
  80611. this._displayGaze = true;
  80612. this._displayLaserPointer = true;
  80613. this._onResize = function () {
  80614. _this.moveButtonToBottomRight();
  80615. if (_this._fullscreenVRpresenting && _this._webVRready) {
  80616. _this.exitVR();
  80617. }
  80618. };
  80619. this._onFullscreenChange = function () {
  80620. if (document.fullscreen !== undefined) {
  80621. _this._fullscreenVRpresenting = document.fullscreen;
  80622. }
  80623. else if (document.mozFullScreen !== undefined) {
  80624. _this._fullscreenVRpresenting = document.mozFullScreen;
  80625. }
  80626. else if (document.webkitIsFullScreen !== undefined) {
  80627. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  80628. }
  80629. else if (document.msIsFullScreen !== undefined) {
  80630. _this._fullscreenVRpresenting = document.msIsFullScreen;
  80631. }
  80632. if (!_this._fullscreenVRpresenting && _this._canvas) {
  80633. _this.exitVR();
  80634. if (!_this._useCustomVRButton) {
  80635. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  80636. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  80637. }
  80638. }
  80639. };
  80640. this.beforeRender = function () {
  80641. if (_this.leftController && _this.leftController._activePointer) {
  80642. _this._castRayAndSelectObject(_this.leftController);
  80643. }
  80644. if (_this.rightController && _this.rightController._activePointer) {
  80645. _this._castRayAndSelectObject(_this.rightController);
  80646. }
  80647. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  80648. _this._castRayAndSelectObject(_this._cameraGazer);
  80649. }
  80650. else {
  80651. _this._cameraGazer._gazeTracker.isVisible = false;
  80652. }
  80653. };
  80654. this._onNewGamepadConnected = function (gamepad) {
  80655. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  80656. if (gamepad.leftStick) {
  80657. gamepad.onleftstickchanged(function (stickValues) {
  80658. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  80659. // Listening to classic/xbox gamepad only if no VR controller is active
  80660. if ((!_this.leftController && !_this.rightController) ||
  80661. ((_this.leftController && !_this.leftController._activePointer) &&
  80662. (_this.rightController && !_this.rightController._activePointer))) {
  80663. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  80664. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  80665. }
  80666. }
  80667. });
  80668. }
  80669. if (gamepad.rightStick) {
  80670. gamepad.onrightstickchanged(function (stickValues) {
  80671. if (_this._teleportationInitialized) {
  80672. _this._checkRotate(stickValues, _this._cameraGazer);
  80673. }
  80674. });
  80675. }
  80676. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  80677. gamepad.onbuttondown(function (buttonPressed) {
  80678. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  80679. _this._cameraGazer._selectionPointerDown();
  80680. }
  80681. });
  80682. gamepad.onbuttonup(function (buttonPressed) {
  80683. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  80684. _this._cameraGazer._selectionPointerUp();
  80685. }
  80686. });
  80687. }
  80688. }
  80689. else {
  80690. var webVRController = gamepad;
  80691. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  80692. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  80693. _this.rightController = controller;
  80694. }
  80695. else {
  80696. _this.leftController = controller;
  80697. }
  80698. _this._tryEnableInteractionOnController(controller);
  80699. }
  80700. };
  80701. // 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
  80702. this._tryEnableInteractionOnController = function (controller) {
  80703. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  80704. _this._enableInteractionOnController(controller);
  80705. }
  80706. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  80707. _this._enableTeleportationOnController(controller);
  80708. }
  80709. };
  80710. this._onNewGamepadDisconnected = function (gamepad) {
  80711. if (gamepad instanceof BABYLON.WebVRController) {
  80712. if (gamepad.hand === "left" && _this.leftController != null) {
  80713. _this.leftController.dispose();
  80714. _this.leftController = null;
  80715. }
  80716. if (gamepad.hand === "right" && _this.rightController != null) {
  80717. _this.rightController.dispose();
  80718. _this.rightController = null;
  80719. }
  80720. }
  80721. };
  80722. this._workingVector = BABYLON.Vector3.Zero();
  80723. this._workingQuaternion = BABYLON.Quaternion.Identity();
  80724. this._workingMatrix = BABYLON.Matrix.Identity();
  80725. this._scene = scene;
  80726. this._canvas = scene.getEngine().getRenderingCanvas();
  80727. // Parse options
  80728. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  80729. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  80730. }
  80731. if (webVROptions.createDeviceOrientationCamera === undefined) {
  80732. webVROptions.createDeviceOrientationCamera = true;
  80733. }
  80734. if (webVROptions.defaultHeight === undefined) {
  80735. webVROptions.defaultHeight = 1.7;
  80736. }
  80737. if (webVROptions.useCustomVRButton) {
  80738. this._useCustomVRButton = true;
  80739. if (webVROptions.customVRButton) {
  80740. this._btnVR = webVROptions.customVRButton;
  80741. }
  80742. }
  80743. if (webVROptions.rayLength) {
  80744. this._rayLength = webVROptions.rayLength;
  80745. }
  80746. this._defaultHeight = webVROptions.defaultHeight;
  80747. // Set position
  80748. if (this._scene.activeCamera) {
  80749. this._position = this._scene.activeCamera.position.clone();
  80750. }
  80751. else {
  80752. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  80753. }
  80754. // Set non-vr camera
  80755. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  80756. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  80757. // Copy data from existing camera
  80758. if (this._scene.activeCamera) {
  80759. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  80760. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  80761. // Set rotation from previous camera
  80762. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  80763. var targetCamera = this._scene.activeCamera;
  80764. if (targetCamera.rotationQuaternion) {
  80765. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  80766. }
  80767. else {
  80768. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  80769. }
  80770. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  80771. }
  80772. }
  80773. this._scene.activeCamera = this._deviceOrientationCamera;
  80774. if (this._canvas) {
  80775. this._scene.activeCamera.attachControl(this._canvas);
  80776. }
  80777. }
  80778. else {
  80779. this._existingCamera = this._scene.activeCamera;
  80780. }
  80781. // Create VR cameras
  80782. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  80783. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  80784. }
  80785. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  80786. this._webVRCamera.useStandingMatrix();
  80787. // Create default button
  80788. if (!this._useCustomVRButton) {
  80789. this._btnVR = document.createElement("BUTTON");
  80790. this._btnVR.className = "babylonVRicon";
  80791. this._btnVR.id = "babylonVRiconbtn";
  80792. this._btnVR.title = "Click to switch to VR";
  80793. 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) }";
  80794. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  80795. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  80796. // css += ".babylonVRicon.vrdisplaysupported { }";
  80797. // css += ".babylonVRicon.vrdisplayready { }";
  80798. // css += ".babylonVRicon.vrdisplayrequesting { }";
  80799. var style = document.createElement('style');
  80800. style.appendChild(document.createTextNode(css));
  80801. document.getElementsByTagName('head')[0].appendChild(style);
  80802. this.moveButtonToBottomRight();
  80803. }
  80804. // VR button click event
  80805. if (this._btnVR) {
  80806. this._btnVR.addEventListener("click", function () {
  80807. if (!_this.isInVRMode) {
  80808. _this.enterVR();
  80809. }
  80810. else {
  80811. _this.exitVR();
  80812. }
  80813. });
  80814. }
  80815. // Window events
  80816. window.addEventListener("resize", this._onResize);
  80817. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  80818. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  80819. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  80820. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  80821. // Display vr button when headset is connected
  80822. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  80823. this.displayVRButton();
  80824. }
  80825. else {
  80826. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  80827. if (e.vrDisplay) {
  80828. _this.displayVRButton();
  80829. }
  80830. });
  80831. }
  80832. // Exiting VR mode using 'ESC' key on desktop
  80833. this._onKeyDown = function (event) {
  80834. if (event.keyCode === 27 && _this.isInVRMode) {
  80835. _this.exitVR();
  80836. }
  80837. };
  80838. document.addEventListener("keydown", this._onKeyDown);
  80839. // Exiting VR mode double tapping the touch screen
  80840. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  80841. if (_this.isInVRMode) {
  80842. _this.exitVR();
  80843. if (_this._fullscreenVRpresenting) {
  80844. _this._scene.getEngine().switchFullscreen(true);
  80845. }
  80846. }
  80847. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  80848. // Listen for WebVR display changes
  80849. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  80850. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  80851. this._onVRRequestPresentStart = function () {
  80852. _this._webVRrequesting = true;
  80853. _this.updateButtonVisibility();
  80854. };
  80855. this._onVRRequestPresentComplete = function (success) {
  80856. _this._webVRrequesting = false;
  80857. _this.updateButtonVisibility();
  80858. };
  80859. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  80860. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  80861. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  80862. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  80863. scene.onDisposeObservable.add(function () {
  80864. _this.dispose();
  80865. });
  80866. // Gamepad connection events
  80867. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  80868. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  80869. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  80870. this.updateButtonVisibility();
  80871. //create easing functions
  80872. this._circleEase = new BABYLON.CircleEase();
  80873. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  80874. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  80875. }
  80876. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  80877. /** Return this.onEnteringVRObservable
  80878. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  80879. */
  80880. get: function () {
  80881. return this.onEnteringVRObservable;
  80882. },
  80883. enumerable: true,
  80884. configurable: true
  80885. });
  80886. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  80887. /** Return this.onExitingVRObservable
  80888. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  80889. */
  80890. get: function () {
  80891. return this.onExitingVRObservable;
  80892. },
  80893. enumerable: true,
  80894. configurable: true
  80895. });
  80896. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  80897. /** Return this.onControllerMeshLoadedObservable
  80898. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  80899. */
  80900. get: function () {
  80901. return this.onControllerMeshLoadedObservable;
  80902. },
  80903. enumerable: true,
  80904. configurable: true
  80905. });
  80906. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  80907. /**
  80908. * The mesh used to display where the user is going to teleport.
  80909. */
  80910. get: function () {
  80911. return this._teleportationTarget;
  80912. },
  80913. /**
  80914. * Sets the mesh to be used to display where the user is going to teleport.
  80915. */
  80916. set: function (value) {
  80917. if (value) {
  80918. value.name = "teleportationTarget";
  80919. this._isDefaultTeleportationTarget = false;
  80920. this._teleportationTarget = value;
  80921. }
  80922. },
  80923. enumerable: true,
  80924. configurable: true
  80925. });
  80926. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  80927. /**
  80928. * The mesh used to display where the user is selecting,
  80929. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  80930. * See http://doc.babylonjs.com/resources/baking_transformations
  80931. */
  80932. get: function () {
  80933. return this._cameraGazer._gazeTracker;
  80934. },
  80935. set: function (value) {
  80936. if (value) {
  80937. this._cameraGazer._gazeTracker = value;
  80938. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  80939. this._cameraGazer._gazeTracker.isPickable = false;
  80940. this._cameraGazer._gazeTracker.isVisible = false;
  80941. this._cameraGazer._gazeTracker.name = "gazeTracker";
  80942. if (this.leftController) {
  80943. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  80944. }
  80945. if (this.rightController) {
  80946. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  80947. }
  80948. }
  80949. },
  80950. enumerable: true,
  80951. configurable: true
  80952. });
  80953. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  80954. /**
  80955. * If the ray of the gaze should be displayed.
  80956. */
  80957. get: function () {
  80958. return this._displayGaze;
  80959. },
  80960. /**
  80961. * Sets if the ray of the gaze should be displayed.
  80962. */
  80963. set: function (value) {
  80964. this._displayGaze = value;
  80965. if (!value) {
  80966. this._cameraGazer._gazeTracker.isVisible = false;
  80967. if (this.leftController) {
  80968. this.leftController._gazeTracker.isVisible = false;
  80969. }
  80970. if (this.rightController) {
  80971. this.rightController._gazeTracker.isVisible = false;
  80972. }
  80973. }
  80974. },
  80975. enumerable: true,
  80976. configurable: true
  80977. });
  80978. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  80979. /**
  80980. * If the ray of the LaserPointer should be displayed.
  80981. */
  80982. get: function () {
  80983. return this._displayLaserPointer;
  80984. },
  80985. /**
  80986. * Sets if the ray of the LaserPointer should be displayed.
  80987. */
  80988. set: function (value) {
  80989. this._displayLaserPointer = value;
  80990. if (!value) {
  80991. if (this.rightController) {
  80992. this.rightController._deactivatePointer();
  80993. this.rightController._gazeTracker.isVisible = false;
  80994. }
  80995. if (this.leftController) {
  80996. this.leftController._deactivatePointer();
  80997. this.leftController._gazeTracker.isVisible = false;
  80998. }
  80999. }
  81000. else {
  81001. if (this.rightController) {
  81002. this.rightController._activatePointer();
  81003. }
  81004. else if (this.leftController) {
  81005. this.leftController._activatePointer();
  81006. }
  81007. }
  81008. },
  81009. enumerable: true,
  81010. configurable: true
  81011. });
  81012. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  81013. /**
  81014. * The deviceOrientationCamera used as the camera when not in VR.
  81015. */
  81016. get: function () {
  81017. return this._deviceOrientationCamera;
  81018. },
  81019. enumerable: true,
  81020. configurable: true
  81021. });
  81022. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  81023. /**
  81024. * Based on the current WebVR support, returns the current VR camera used.
  81025. */
  81026. get: function () {
  81027. if (this._webVRready) {
  81028. return this._webVRCamera;
  81029. }
  81030. else {
  81031. return this._scene.activeCamera;
  81032. }
  81033. },
  81034. enumerable: true,
  81035. configurable: true
  81036. });
  81037. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  81038. /**
  81039. * The webVRCamera which is used when in VR.
  81040. */
  81041. get: function () {
  81042. return this._webVRCamera;
  81043. },
  81044. enumerable: true,
  81045. configurable: true
  81046. });
  81047. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  81048. /**
  81049. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  81050. */
  81051. get: function () {
  81052. return this._vrDeviceOrientationCamera;
  81053. },
  81054. enumerable: true,
  81055. configurable: true
  81056. });
  81057. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  81058. get: function () {
  81059. var result = this._cameraGazer._teleportationRequestInitiated
  81060. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  81061. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  81062. return result;
  81063. },
  81064. enumerable: true,
  81065. configurable: true
  81066. });
  81067. // Raised when one of the controller has loaded successfully its associated default mesh
  81068. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  81069. if (this.leftController && this.leftController.webVRController == webVRController) {
  81070. this._tryEnableInteractionOnController(this.leftController);
  81071. }
  81072. if (this.rightController && this.rightController.webVRController == webVRController) {
  81073. this._tryEnableInteractionOnController(this.rightController);
  81074. }
  81075. try {
  81076. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  81077. }
  81078. catch (err) {
  81079. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  81080. }
  81081. };
  81082. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  81083. /**
  81084. * Gets a value indicating if we are currently in VR mode.
  81085. */
  81086. get: function () {
  81087. return this._webVRpresenting || this._fullscreenVRpresenting;
  81088. },
  81089. enumerable: true,
  81090. configurable: true
  81091. });
  81092. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  81093. var vrDisplay = this._scene.getEngine().getVRDevice();
  81094. if (vrDisplay) {
  81095. var wasPresenting = this._webVRpresenting;
  81096. // A VR display is connected
  81097. this._webVRpresenting = vrDisplay.isPresenting;
  81098. if (wasPresenting && !this._webVRpresenting)
  81099. this.exitVR();
  81100. }
  81101. else {
  81102. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  81103. }
  81104. this.updateButtonVisibility();
  81105. };
  81106. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  81107. this._webVRsupported = eventArgs.vrSupported;
  81108. this._webVRready = !!eventArgs.vrDisplay;
  81109. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  81110. this.updateButtonVisibility();
  81111. };
  81112. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  81113. if (this._canvas && !this._useCustomVRButton) {
  81114. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  81115. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  81116. }
  81117. };
  81118. VRExperienceHelper.prototype.displayVRButton = function () {
  81119. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  81120. document.body.appendChild(this._btnVR);
  81121. this._btnVRDisplayed = true;
  81122. }
  81123. };
  81124. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  81125. if (!this._btnVR || this._useCustomVRButton) {
  81126. return;
  81127. }
  81128. this._btnVR.className = "babylonVRicon";
  81129. if (this.isInVRMode) {
  81130. this._btnVR.className += " vrdisplaypresenting";
  81131. }
  81132. else {
  81133. if (this._webVRready)
  81134. this._btnVR.className += " vrdisplayready";
  81135. if (this._webVRsupported)
  81136. this._btnVR.className += " vrdisplaysupported";
  81137. if (this._webVRrequesting)
  81138. this._btnVR.className += " vrdisplayrequesting";
  81139. }
  81140. };
  81141. /**
  81142. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  81143. * Otherwise, will use the fullscreen API.
  81144. */
  81145. VRExperienceHelper.prototype.enterVR = function () {
  81146. if (this.onEnteringVRObservable) {
  81147. try {
  81148. this.onEnteringVRObservable.notifyObservers(this);
  81149. }
  81150. catch (err) {
  81151. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  81152. }
  81153. }
  81154. if (this._scene.activeCamera) {
  81155. this._position = this._scene.activeCamera.position.clone();
  81156. // make sure that we return to the last active camera
  81157. this._existingCamera = this._scene.activeCamera;
  81158. }
  81159. if (this._webVRrequesting)
  81160. return;
  81161. // If WebVR is supported and a headset is connected
  81162. if (this._webVRready) {
  81163. if (!this._webVRpresenting) {
  81164. this._webVRCamera.position = this._position;
  81165. this._scene.activeCamera = this._webVRCamera;
  81166. }
  81167. }
  81168. else if (this._vrDeviceOrientationCamera) {
  81169. this._vrDeviceOrientationCamera.position = this._position;
  81170. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  81171. this._scene.getEngine().switchFullscreen(true);
  81172. this.updateButtonVisibility();
  81173. }
  81174. if (this._scene.activeCamera && this._canvas) {
  81175. this._scene.activeCamera.attachControl(this._canvas);
  81176. }
  81177. if (this._interactionsEnabled) {
  81178. this._scene.registerBeforeRender(this.beforeRender);
  81179. }
  81180. };
  81181. /**
  81182. * Attempt to exit VR, or fullscreen.
  81183. */
  81184. VRExperienceHelper.prototype.exitVR = function () {
  81185. if (this.onExitingVRObservable) {
  81186. try {
  81187. this.onExitingVRObservable.notifyObservers(this);
  81188. }
  81189. catch (err) {
  81190. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  81191. }
  81192. }
  81193. if (this._webVRpresenting) {
  81194. this._scene.getEngine().disableVR();
  81195. }
  81196. if (this._scene.activeCamera) {
  81197. this._position = this._scene.activeCamera.position.clone();
  81198. }
  81199. if (this._deviceOrientationCamera) {
  81200. this._deviceOrientationCamera.position = this._position;
  81201. this._scene.activeCamera = this._deviceOrientationCamera;
  81202. if (this._canvas) {
  81203. this._scene.activeCamera.attachControl(this._canvas);
  81204. }
  81205. }
  81206. else if (this._existingCamera) {
  81207. this._existingCamera.position = this._position;
  81208. this._scene.activeCamera = this._existingCamera;
  81209. }
  81210. this.updateButtonVisibility();
  81211. if (this._interactionsEnabled) {
  81212. this._scene.unregisterBeforeRender(this.beforeRender);
  81213. }
  81214. };
  81215. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  81216. /**
  81217. * The position of the vr experience helper.
  81218. */
  81219. get: function () {
  81220. return this._position;
  81221. },
  81222. /**
  81223. * Sets the position of the vr experience helper.
  81224. */
  81225. set: function (value) {
  81226. this._position = value;
  81227. if (this._scene.activeCamera) {
  81228. this._scene.activeCamera.position = value;
  81229. }
  81230. },
  81231. enumerable: true,
  81232. configurable: true
  81233. });
  81234. /**
  81235. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  81236. */
  81237. VRExperienceHelper.prototype.enableInteractions = function () {
  81238. var _this = this;
  81239. if (!this._interactionsEnabled) {
  81240. this._interactionsRequested = true;
  81241. if (this.leftController) {
  81242. this._enableInteractionOnController(this.leftController);
  81243. }
  81244. if (this.rightController) {
  81245. this._enableInteractionOnController(this.rightController);
  81246. }
  81247. this.raySelectionPredicate = function (mesh) {
  81248. return mesh.isVisible;
  81249. };
  81250. this.meshSelectionPredicate = function (mesh) {
  81251. return true;
  81252. };
  81253. this._raySelectionPredicate = function (mesh) {
  81254. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  81255. && mesh.name.indexOf("teleportationTarget") === -1
  81256. && mesh.name.indexOf("torusTeleportation") === -1
  81257. && mesh.name.indexOf("laserPointer") === -1)) {
  81258. return _this.raySelectionPredicate(mesh);
  81259. }
  81260. return false;
  81261. };
  81262. this._interactionsEnabled = true;
  81263. }
  81264. };
  81265. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  81266. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  81267. if (this._floorMeshesCollection[i].id === mesh.id) {
  81268. return true;
  81269. }
  81270. }
  81271. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  81272. return true;
  81273. }
  81274. return false;
  81275. };
  81276. /**
  81277. * Adds a floor mesh to be used for teleportation.
  81278. * @param floorMesh the mesh to be used for teleportation.
  81279. */
  81280. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  81281. if (!this._floorMeshesCollection) {
  81282. return;
  81283. }
  81284. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  81285. return;
  81286. }
  81287. this._floorMeshesCollection.push(floorMesh);
  81288. };
  81289. /**
  81290. * Removes a floor mesh from being used for teleportation.
  81291. * @param floorMesh the mesh to be removed.
  81292. */
  81293. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  81294. if (!this._floorMeshesCollection) {
  81295. return;
  81296. }
  81297. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  81298. if (meshIndex !== -1) {
  81299. this._floorMeshesCollection.splice(meshIndex, 1);
  81300. }
  81301. };
  81302. /**
  81303. * Enables interactions and teleportation using the VR controllers and gaze.
  81304. * @param vrTeleportationOptions options to modify teleportation behavior.
  81305. */
  81306. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  81307. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  81308. if (!this._teleportationInitialized) {
  81309. this._teleportationRequested = true;
  81310. this.enableInteractions();
  81311. if (vrTeleportationOptions.floorMeshName) {
  81312. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  81313. }
  81314. if (vrTeleportationOptions.floorMeshes) {
  81315. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  81316. }
  81317. if (this.leftController != null) {
  81318. this._enableTeleportationOnController(this.leftController);
  81319. }
  81320. if (this.rightController != null) {
  81321. this._enableTeleportationOnController(this.rightController);
  81322. }
  81323. // Creates an image processing post process for the vignette not relying
  81324. // on the main scene configuration for image processing to reduce setup and spaces
  81325. // (gamma/linear) conflicts.
  81326. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  81327. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  81328. imageProcessingConfiguration.vignetteEnabled = true;
  81329. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  81330. this._webVRCamera.detachPostProcess(this._postProcessMove);
  81331. this._teleportationInitialized = true;
  81332. if (this._isDefaultTeleportationTarget) {
  81333. this._createTeleportationCircles();
  81334. }
  81335. }
  81336. };
  81337. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  81338. var _this = this;
  81339. var controllerMesh = controller.webVRController.mesh;
  81340. if (controllerMesh) {
  81341. var makeNotPick = function (root) {
  81342. root.name += " laserPointer";
  81343. root.getChildMeshes().forEach(function (c) {
  81344. makeNotPick(c);
  81345. });
  81346. };
  81347. makeNotPick(controllerMesh);
  81348. var childMeshes = controllerMesh.getChildMeshes();
  81349. for (var i = 0; i < childMeshes.length; i++) {
  81350. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  81351. controllerMesh = childMeshes[i];
  81352. break;
  81353. }
  81354. }
  81355. controller._setLaserPointerParent(controllerMesh);
  81356. controller._interactionsEnabled = true;
  81357. controller._activatePointer();
  81358. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  81359. // Enabling / disabling laserPointer
  81360. if (_this._displayLaserPointer && stateObject.value === 1) {
  81361. if (controller._activePointer) {
  81362. controller._deactivatePointer();
  81363. }
  81364. else {
  81365. controller._activatePointer();
  81366. }
  81367. if (_this.displayGaze) {
  81368. controller._gazeTracker.isVisible = controller._activePointer;
  81369. }
  81370. }
  81371. });
  81372. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  81373. if (!controller._pointerDownOnMeshAsked) {
  81374. if (stateObject.value > _this._padSensibilityUp) {
  81375. controller._selectionPointerDown();
  81376. }
  81377. }
  81378. else if (stateObject.value < _this._padSensibilityDown) {
  81379. controller._selectionPointerUp();
  81380. }
  81381. });
  81382. }
  81383. };
  81384. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  81385. // Dont teleport if another gaze already requested teleportation
  81386. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  81387. return;
  81388. }
  81389. if (!gazer._teleportationRequestInitiated) {
  81390. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  81391. gazer._activatePointer();
  81392. gazer._teleportationRequestInitiated = true;
  81393. }
  81394. }
  81395. else {
  81396. // Listening to the proper controller values changes to confirm teleportation
  81397. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  81398. if (this._teleportActive) {
  81399. this._teleportCamera(this._haloCenter);
  81400. }
  81401. gazer._teleportationRequestInitiated = false;
  81402. }
  81403. }
  81404. };
  81405. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  81406. // Only rotate when user is not currently selecting a teleportation location
  81407. if (gazer._teleportationRequestInitiated) {
  81408. return;
  81409. }
  81410. if (!this._rotationLeftAsked) {
  81411. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  81412. this._rotationLeftAsked = true;
  81413. if (this._rotationAllowed) {
  81414. this._rotateCamera(false);
  81415. }
  81416. }
  81417. }
  81418. else {
  81419. if (stateObject.x > -this._padSensibilityDown) {
  81420. this._rotationLeftAsked = false;
  81421. }
  81422. }
  81423. if (!this._rotationRightAsked) {
  81424. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  81425. this._rotationRightAsked = true;
  81426. if (this._rotationAllowed) {
  81427. this._rotateCamera(true);
  81428. }
  81429. }
  81430. }
  81431. else {
  81432. if (stateObject.x < this._padSensibilityDown) {
  81433. this._rotationRightAsked = false;
  81434. }
  81435. }
  81436. };
  81437. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  81438. // Only teleport backwards when user is not currently selecting a teleportation location
  81439. if (gazer._teleportationRequestInitiated) {
  81440. return;
  81441. }
  81442. // Teleport backwards
  81443. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  81444. if (!gazer._teleportationBackRequestInitiated) {
  81445. if (!this.currentVRCamera) {
  81446. return;
  81447. }
  81448. // Get rotation and position of the current camera
  81449. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  81450. var position = this.currentVRCamera.position;
  81451. // If the camera has device position, use that instead
  81452. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  81453. rotation = this.currentVRCamera.deviceRotationQuaternion;
  81454. position = this.currentVRCamera.devicePosition;
  81455. }
  81456. // Get matrix with only the y rotation of the device rotation
  81457. rotation.toEulerAnglesToRef(this._workingVector);
  81458. this._workingVector.z = 0;
  81459. this._workingVector.x = 0;
  81460. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  81461. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  81462. // Rotate backwards ray by device rotation to cast at the ground behind the user
  81463. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  81464. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  81465. var ray = new BABYLON.Ray(position, this._workingVector);
  81466. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  81467. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  81468. this._teleportCamera(hit.pickedPoint);
  81469. }
  81470. gazer._teleportationBackRequestInitiated = true;
  81471. }
  81472. }
  81473. else {
  81474. gazer._teleportationBackRequestInitiated = false;
  81475. }
  81476. };
  81477. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  81478. var _this = this;
  81479. var controllerMesh = controller.webVRController.mesh;
  81480. if (controllerMesh) {
  81481. if (!controller._interactionsEnabled) {
  81482. this._enableInteractionOnController(controller);
  81483. }
  81484. controller._interactionsEnabled = true;
  81485. controller._teleportationEnabled = true;
  81486. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  81487. controller._dpadPressed = false;
  81488. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  81489. controller._dpadPressed = stateObject.pressed;
  81490. if (!controller._dpadPressed) {
  81491. _this._rotationLeftAsked = false;
  81492. _this._rotationRightAsked = false;
  81493. controller._teleportationBackRequestInitiated = false;
  81494. }
  81495. });
  81496. }
  81497. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  81498. if (_this.teleportationEnabled) {
  81499. _this._checkTeleportBackwards(stateObject, controller);
  81500. _this._checkTeleportWithRay(stateObject, controller);
  81501. }
  81502. _this._checkRotate(stateObject, controller);
  81503. });
  81504. }
  81505. };
  81506. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  81507. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  81508. this._teleportationTarget.isPickable = false;
  81509. var length = 512;
  81510. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  81511. dynamicTexture.hasAlpha = true;
  81512. var context = dynamicTexture.getContext();
  81513. var centerX = length / 2;
  81514. var centerY = length / 2;
  81515. var radius = 200;
  81516. context.beginPath();
  81517. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  81518. context.fillStyle = this._teleportationFillColor;
  81519. context.fill();
  81520. context.lineWidth = 10;
  81521. context.strokeStyle = this._teleportationBorderColor;
  81522. context.stroke();
  81523. context.closePath();
  81524. dynamicTexture.update();
  81525. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  81526. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  81527. this._teleportationTarget.material = teleportationCircleMaterial;
  81528. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  81529. torus.isPickable = false;
  81530. torus.parent = this._teleportationTarget;
  81531. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  81532. var keys = [];
  81533. keys.push({
  81534. frame: 0,
  81535. value: 0
  81536. });
  81537. keys.push({
  81538. frame: 30,
  81539. value: 0.4
  81540. });
  81541. keys.push({
  81542. frame: 60,
  81543. value: 0
  81544. });
  81545. animationInnerCircle.setKeys(keys);
  81546. var easingFunction = new BABYLON.SineEase();
  81547. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  81548. animationInnerCircle.setEasingFunction(easingFunction);
  81549. torus.animations = [];
  81550. torus.animations.push(animationInnerCircle);
  81551. this._scene.beginAnimation(torus, 0, 60, true);
  81552. this._hideTeleportationTarget();
  81553. };
  81554. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  81555. this._teleportActive = true;
  81556. if (this._teleportationInitialized) {
  81557. this._teleportationTarget.isVisible = true;
  81558. if (this._isDefaultTeleportationTarget) {
  81559. this._teleportationTarget.getChildren()[0].isVisible = true;
  81560. }
  81561. }
  81562. };
  81563. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  81564. this._teleportActive = false;
  81565. if (this._teleportationInitialized) {
  81566. this._teleportationTarget.isVisible = false;
  81567. if (this._isDefaultTeleportationTarget) {
  81568. this._teleportationTarget.getChildren()[0].isVisible = false;
  81569. }
  81570. }
  81571. };
  81572. VRExperienceHelper.prototype._rotateCamera = function (right) {
  81573. var _this = this;
  81574. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81575. return;
  81576. }
  81577. if (right) {
  81578. this._rotationAngle++;
  81579. }
  81580. else {
  81581. this._rotationAngle--;
  81582. }
  81583. this.currentVRCamera.animations = [];
  81584. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  81585. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81586. var animationRotationKeys = [];
  81587. animationRotationKeys.push({
  81588. frame: 0,
  81589. value: this.currentVRCamera.rotationQuaternion
  81590. });
  81591. animationRotationKeys.push({
  81592. frame: 6,
  81593. value: target
  81594. });
  81595. animationRotation.setKeys(animationRotationKeys);
  81596. animationRotation.setEasingFunction(this._circleEase);
  81597. this.currentVRCamera.animations.push(animationRotation);
  81598. this._postProcessMove.animations = [];
  81599. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81600. var vignetteWeightKeys = [];
  81601. vignetteWeightKeys.push({
  81602. frame: 0,
  81603. value: 0
  81604. });
  81605. vignetteWeightKeys.push({
  81606. frame: 3,
  81607. value: 4
  81608. });
  81609. vignetteWeightKeys.push({
  81610. frame: 6,
  81611. value: 0
  81612. });
  81613. animationPP.setKeys(vignetteWeightKeys);
  81614. animationPP.setEasingFunction(this._circleEase);
  81615. this._postProcessMove.animations.push(animationPP);
  81616. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81617. var vignetteStretchKeys = [];
  81618. vignetteStretchKeys.push({
  81619. frame: 0,
  81620. value: 0
  81621. });
  81622. vignetteStretchKeys.push({
  81623. frame: 3,
  81624. value: 10
  81625. });
  81626. vignetteStretchKeys.push({
  81627. frame: 6,
  81628. value: 0
  81629. });
  81630. animationPP2.setKeys(vignetteStretchKeys);
  81631. animationPP2.setEasingFunction(this._circleEase);
  81632. this._postProcessMove.animations.push(animationPP2);
  81633. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  81634. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  81635. this._postProcessMove.samples = 4;
  81636. this._webVRCamera.attachPostProcess(this._postProcessMove);
  81637. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  81638. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  81639. });
  81640. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  81641. };
  81642. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  81643. if (hit.pickedPoint) {
  81644. if (gazer._teleportationRequestInitiated) {
  81645. this._displayTeleportationTarget();
  81646. this._haloCenter.copyFrom(hit.pickedPoint);
  81647. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  81648. }
  81649. var pickNormal = hit.getNormal(true, false);
  81650. if (pickNormal) {
  81651. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  81652. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  81653. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  81654. }
  81655. this._teleportationTarget.position.y += 0.1;
  81656. }
  81657. };
  81658. VRExperienceHelper.prototype._teleportCamera = function (location) {
  81659. var _this = this;
  81660. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81661. return;
  81662. }
  81663. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  81664. // offset of the headset from the anchor.
  81665. if (this.webVRCamera.leftCamera) {
  81666. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  81667. this._workingVector.subtractInPlace(this.webVRCamera.position);
  81668. location.subtractToRef(this._workingVector, this._workingVector);
  81669. }
  81670. else {
  81671. this._workingVector.copyFrom(location);
  81672. }
  81673. // Add height to account for user's height offset
  81674. if (this.isInVRMode) {
  81675. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  81676. }
  81677. else {
  81678. this._workingVector.y += this._defaultHeight;
  81679. }
  81680. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  81681. // Create animation from the camera's position to the new location
  81682. this.currentVRCamera.animations = [];
  81683. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81684. var animationCameraTeleportationKeys = [{
  81685. frame: 0,
  81686. value: this.currentVRCamera.position
  81687. },
  81688. {
  81689. frame: 11,
  81690. value: this._workingVector
  81691. }
  81692. ];
  81693. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  81694. animationCameraTeleportation.setEasingFunction(this._circleEase);
  81695. this.currentVRCamera.animations.push(animationCameraTeleportation);
  81696. this._postProcessMove.animations = [];
  81697. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81698. var vignetteWeightKeys = [];
  81699. vignetteWeightKeys.push({
  81700. frame: 0,
  81701. value: 0
  81702. });
  81703. vignetteWeightKeys.push({
  81704. frame: 5,
  81705. value: 8
  81706. });
  81707. vignetteWeightKeys.push({
  81708. frame: 11,
  81709. value: 0
  81710. });
  81711. animationPP.setKeys(vignetteWeightKeys);
  81712. this._postProcessMove.animations.push(animationPP);
  81713. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81714. var vignetteStretchKeys = [];
  81715. vignetteStretchKeys.push({
  81716. frame: 0,
  81717. value: 0
  81718. });
  81719. vignetteStretchKeys.push({
  81720. frame: 5,
  81721. value: 10
  81722. });
  81723. vignetteStretchKeys.push({
  81724. frame: 11,
  81725. value: 0
  81726. });
  81727. animationPP2.setKeys(vignetteStretchKeys);
  81728. this._postProcessMove.animations.push(animationPP2);
  81729. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  81730. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  81731. this._webVRCamera.attachPostProcess(this._postProcessMove);
  81732. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  81733. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  81734. });
  81735. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  81736. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  81737. });
  81738. this._hideTeleportationTarget();
  81739. };
  81740. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  81741. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81742. return;
  81743. }
  81744. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  81745. // Moving the gazeTracker on the mesh face targetted
  81746. if (hit && hit.pickedPoint) {
  81747. if (this._displayGaze) {
  81748. var multiplier = 1;
  81749. gazer._gazeTracker.isVisible = true;
  81750. if (gazer._isActionableMesh) {
  81751. multiplier = 3;
  81752. }
  81753. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  81754. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  81755. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  81756. var pickNormal = hit.getNormal();
  81757. // To avoid z-fighting
  81758. var deltaFighting = 0.002;
  81759. if (pickNormal) {
  81760. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  81761. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  81762. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  81763. }
  81764. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  81765. if (gazer._gazeTracker.position.x < 0) {
  81766. gazer._gazeTracker.position.x += deltaFighting;
  81767. }
  81768. else {
  81769. gazer._gazeTracker.position.x -= deltaFighting;
  81770. }
  81771. if (gazer._gazeTracker.position.y < 0) {
  81772. gazer._gazeTracker.position.y += deltaFighting;
  81773. }
  81774. else {
  81775. gazer._gazeTracker.position.y -= deltaFighting;
  81776. }
  81777. if (gazer._gazeTracker.position.z < 0) {
  81778. gazer._gazeTracker.position.z += deltaFighting;
  81779. }
  81780. else {
  81781. gazer._gazeTracker.position.z -= deltaFighting;
  81782. }
  81783. }
  81784. // Changing the size of the laser pointer based on the distance from the targetted point
  81785. gazer._updatePointerDistance(hit.distance);
  81786. }
  81787. else {
  81788. gazer._gazeTracker.isVisible = false;
  81789. }
  81790. if (hit && hit.pickedMesh) {
  81791. gazer._currentHit = hit;
  81792. if (gazer._pointerDownOnMeshAsked) {
  81793. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  81794. }
  81795. // The object selected is the floor, we're in a teleportation scenario
  81796. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  81797. // Moving the teleportation area to this targetted point
  81798. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  81799. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  81800. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  81801. }
  81802. gazer._currentMeshSelected = null;
  81803. if (gazer._teleportationRequestInitiated) {
  81804. this._moveTeleportationSelectorTo(hit, gazer);
  81805. }
  81806. return;
  81807. }
  81808. // If not, we're in a selection scenario
  81809. //this._teleportationAllowed = false;
  81810. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  81811. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  81812. this.onNewMeshPicked.notifyObservers(hit);
  81813. gazer._currentMeshSelected = hit.pickedMesh;
  81814. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  81815. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  81816. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  81817. gazer._isActionableMesh = true;
  81818. }
  81819. else {
  81820. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81821. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81822. gazer._isActionableMesh = false;
  81823. }
  81824. try {
  81825. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  81826. }
  81827. catch (err) {
  81828. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  81829. }
  81830. }
  81831. else {
  81832. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  81833. gazer._currentMeshSelected = null;
  81834. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81835. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81836. }
  81837. }
  81838. }
  81839. else {
  81840. gazer._currentHit = null;
  81841. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  81842. gazer._currentMeshSelected = null;
  81843. //this._teleportationAllowed = false;
  81844. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81845. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81846. }
  81847. };
  81848. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  81849. if (mesh) {
  81850. this.onSelectedMeshUnselected.notifyObservers(mesh);
  81851. }
  81852. };
  81853. /**
  81854. * Sets the color of the laser ray from the vr controllers.
  81855. * @param color new color for the ray.
  81856. */
  81857. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  81858. if (this.leftController) {
  81859. this.leftController._setLaserPointerColor(color);
  81860. }
  81861. if (this.rightController) {
  81862. this.rightController._setLaserPointerColor(color);
  81863. }
  81864. };
  81865. /**
  81866. * Sets the color of the ray from the vr headsets gaze.
  81867. * @param color new color for the ray.
  81868. */
  81869. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  81870. if (!this._cameraGazer._gazeTracker.material) {
  81871. return;
  81872. }
  81873. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  81874. if (this.leftController) {
  81875. this.leftController._gazeTracker.material.emissiveColor = color;
  81876. }
  81877. if (this.rightController) {
  81878. this.rightController._gazeTracker.material.emissiveColor = color;
  81879. }
  81880. };
  81881. /**
  81882. * Exits VR and disposes of the vr experience helper
  81883. */
  81884. VRExperienceHelper.prototype.dispose = function () {
  81885. if (this.isInVRMode) {
  81886. this.exitVR();
  81887. }
  81888. if (this._postProcessMove) {
  81889. this._postProcessMove.dispose();
  81890. }
  81891. if (this._webVRCamera) {
  81892. this._webVRCamera.dispose();
  81893. }
  81894. if (this._vrDeviceOrientationCamera) {
  81895. this._vrDeviceOrientationCamera.dispose();
  81896. }
  81897. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  81898. document.body.removeChild(this._btnVR);
  81899. }
  81900. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  81901. this._deviceOrientationCamera.dispose();
  81902. }
  81903. if (this._cameraGazer) {
  81904. this._cameraGazer.dispose();
  81905. }
  81906. if (this.leftController) {
  81907. this.leftController.dispose();
  81908. }
  81909. if (this.rightController) {
  81910. this.rightController.dispose();
  81911. }
  81912. if (this._teleportationTarget) {
  81913. this._teleportationTarget.dispose();
  81914. }
  81915. this._floorMeshesCollection = [];
  81916. document.removeEventListener("keydown", this._onKeyDown);
  81917. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  81918. window.removeEventListener("resize", this._onResize);
  81919. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  81920. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  81921. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  81922. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  81923. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  81924. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  81925. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  81926. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  81927. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  81928. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  81929. this._scene.unregisterBeforeRender(this.beforeRender);
  81930. };
  81931. /**
  81932. * Gets the name of the VRExperienceHelper class
  81933. * @returns "VRExperienceHelper"
  81934. */
  81935. VRExperienceHelper.prototype.getClassName = function () {
  81936. return "VRExperienceHelper";
  81937. };
  81938. return VRExperienceHelper;
  81939. }());
  81940. BABYLON.VRExperienceHelper = VRExperienceHelper;
  81941. })(BABYLON || (BABYLON = {}));
  81942. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  81943. // Mainly based on these 2 articles :
  81944. // 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
  81945. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  81946. var BABYLON;
  81947. (function (BABYLON) {
  81948. var JoystickAxis;
  81949. (function (JoystickAxis) {
  81950. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  81951. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  81952. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  81953. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  81954. var VirtualJoystick = /** @class */ (function () {
  81955. function VirtualJoystick(leftJoystick) {
  81956. var _this = this;
  81957. if (leftJoystick) {
  81958. this._leftJoystick = true;
  81959. }
  81960. else {
  81961. this._leftJoystick = false;
  81962. }
  81963. VirtualJoystick._globalJoystickIndex++;
  81964. // By default left & right arrow keys are moving the X
  81965. // and up & down keys are moving the Y
  81966. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  81967. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  81968. this.reverseLeftRight = false;
  81969. this.reverseUpDown = false;
  81970. // collections of pointers
  81971. this._touches = new BABYLON.StringDictionary();
  81972. this.deltaPosition = BABYLON.Vector3.Zero();
  81973. this._joystickSensibility = 25;
  81974. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  81975. this._onResize = function (evt) {
  81976. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  81977. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  81978. if (VirtualJoystick.vjCanvas) {
  81979. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  81980. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  81981. }
  81982. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  81983. };
  81984. // injecting a canvas element on top of the canvas 3D game
  81985. if (!VirtualJoystick.vjCanvas) {
  81986. window.addEventListener("resize", this._onResize, false);
  81987. VirtualJoystick.vjCanvas = document.createElement("canvas");
  81988. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  81989. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  81990. VirtualJoystick.vjCanvas.width = window.innerWidth;
  81991. VirtualJoystick.vjCanvas.height = window.innerHeight;
  81992. VirtualJoystick.vjCanvas.style.width = "100%";
  81993. VirtualJoystick.vjCanvas.style.height = "100%";
  81994. VirtualJoystick.vjCanvas.style.position = "absolute";
  81995. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  81996. VirtualJoystick.vjCanvas.style.top = "0px";
  81997. VirtualJoystick.vjCanvas.style.left = "0px";
  81998. VirtualJoystick.vjCanvas.style.zIndex = "5";
  81999. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  82000. // Support for jQuery PEP polyfill
  82001. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  82002. var context = VirtualJoystick.vjCanvas.getContext('2d');
  82003. if (!context) {
  82004. throw new Error("Unable to create canvas for virtual joystick");
  82005. }
  82006. VirtualJoystick.vjCanvasContext = context;
  82007. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  82008. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  82009. document.body.appendChild(VirtualJoystick.vjCanvas);
  82010. }
  82011. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  82012. this.pressed = false;
  82013. // default joystick color
  82014. this._joystickColor = "cyan";
  82015. this._joystickPointerID = -1;
  82016. // current joystick position
  82017. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  82018. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  82019. // origin joystick position
  82020. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  82021. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  82022. this._onPointerDownHandlerRef = function (evt) {
  82023. _this._onPointerDown(evt);
  82024. };
  82025. this._onPointerMoveHandlerRef = function (evt) {
  82026. _this._onPointerMove(evt);
  82027. };
  82028. this._onPointerUpHandlerRef = function (evt) {
  82029. _this._onPointerUp(evt);
  82030. };
  82031. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  82032. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  82033. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  82034. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  82035. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  82036. evt.preventDefault(); // Disables system menu
  82037. }, false);
  82038. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  82039. }
  82040. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  82041. this._joystickSensibility = newJoystickSensibility;
  82042. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  82043. };
  82044. VirtualJoystick.prototype._onPointerDown = function (e) {
  82045. var positionOnScreenCondition;
  82046. e.preventDefault();
  82047. if (this._leftJoystick === true) {
  82048. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  82049. }
  82050. else {
  82051. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  82052. }
  82053. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  82054. // First contact will be dedicated to the virtual joystick
  82055. this._joystickPointerID = e.pointerId;
  82056. this._joystickPointerStartPos.x = e.clientX;
  82057. this._joystickPointerStartPos.y = e.clientY;
  82058. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  82059. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  82060. this._deltaJoystickVector.x = 0;
  82061. this._deltaJoystickVector.y = 0;
  82062. this.pressed = true;
  82063. this._touches.add(e.pointerId.toString(), e);
  82064. }
  82065. else {
  82066. // You can only trigger the action buttons with a joystick declared
  82067. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  82068. this._action();
  82069. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  82070. }
  82071. }
  82072. };
  82073. VirtualJoystick.prototype._onPointerMove = function (e) {
  82074. // If the current pointer is the one associated to the joystick (first touch contact)
  82075. if (this._joystickPointerID == e.pointerId) {
  82076. this._joystickPointerPos.x = e.clientX;
  82077. this._joystickPointerPos.y = e.clientY;
  82078. this._deltaJoystickVector = this._joystickPointerPos.clone();
  82079. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  82080. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  82081. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  82082. switch (this._axisTargetedByLeftAndRight) {
  82083. case JoystickAxis.X:
  82084. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  82085. break;
  82086. case JoystickAxis.Y:
  82087. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  82088. break;
  82089. case JoystickAxis.Z:
  82090. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  82091. break;
  82092. }
  82093. var directionUpDown = this.reverseUpDown ? 1 : -1;
  82094. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  82095. switch (this._axisTargetedByUpAndDown) {
  82096. case JoystickAxis.X:
  82097. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  82098. break;
  82099. case JoystickAxis.Y:
  82100. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  82101. break;
  82102. case JoystickAxis.Z:
  82103. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  82104. break;
  82105. }
  82106. }
  82107. else {
  82108. var data = this._touches.get(e.pointerId.toString());
  82109. if (data) {
  82110. data.x = e.clientX;
  82111. data.y = e.clientY;
  82112. }
  82113. }
  82114. };
  82115. VirtualJoystick.prototype._onPointerUp = function (e) {
  82116. if (this._joystickPointerID == e.pointerId) {
  82117. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  82118. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  82119. this._joystickPointerID = -1;
  82120. this.pressed = false;
  82121. }
  82122. else {
  82123. var touch = this._touches.get(e.pointerId.toString());
  82124. if (touch) {
  82125. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  82126. }
  82127. }
  82128. this._deltaJoystickVector.x = 0;
  82129. this._deltaJoystickVector.y = 0;
  82130. this._touches.remove(e.pointerId.toString());
  82131. };
  82132. /**
  82133. * Change the color of the virtual joystick
  82134. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  82135. */
  82136. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  82137. this._joystickColor = newColor;
  82138. };
  82139. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  82140. this._action = action;
  82141. };
  82142. // Define which axis you'd like to control for left & right
  82143. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  82144. switch (axis) {
  82145. case JoystickAxis.X:
  82146. case JoystickAxis.Y:
  82147. case JoystickAxis.Z:
  82148. this._axisTargetedByLeftAndRight = axis;
  82149. break;
  82150. default:
  82151. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  82152. break;
  82153. }
  82154. };
  82155. // Define which axis you'd like to control for up & down
  82156. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  82157. switch (axis) {
  82158. case JoystickAxis.X:
  82159. case JoystickAxis.Y:
  82160. case JoystickAxis.Z:
  82161. this._axisTargetedByUpAndDown = axis;
  82162. break;
  82163. default:
  82164. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  82165. break;
  82166. }
  82167. };
  82168. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  82169. var _this = this;
  82170. if (this.pressed) {
  82171. this._touches.forEach(function (key, touch) {
  82172. if (touch.pointerId === _this._joystickPointerID) {
  82173. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  82174. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  82175. VirtualJoystick.vjCanvasContext.beginPath();
  82176. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  82177. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  82178. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  82179. VirtualJoystick.vjCanvasContext.stroke();
  82180. VirtualJoystick.vjCanvasContext.closePath();
  82181. VirtualJoystick.vjCanvasContext.beginPath();
  82182. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  82183. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  82184. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  82185. VirtualJoystick.vjCanvasContext.stroke();
  82186. VirtualJoystick.vjCanvasContext.closePath();
  82187. VirtualJoystick.vjCanvasContext.beginPath();
  82188. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  82189. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  82190. VirtualJoystick.vjCanvasContext.stroke();
  82191. VirtualJoystick.vjCanvasContext.closePath();
  82192. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  82193. }
  82194. else {
  82195. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  82196. VirtualJoystick.vjCanvasContext.beginPath();
  82197. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  82198. VirtualJoystick.vjCanvasContext.beginPath();
  82199. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  82200. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  82201. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  82202. VirtualJoystick.vjCanvasContext.stroke();
  82203. VirtualJoystick.vjCanvasContext.closePath();
  82204. touch.prevX = touch.x;
  82205. touch.prevY = touch.y;
  82206. }
  82207. ;
  82208. });
  82209. }
  82210. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  82211. };
  82212. VirtualJoystick.prototype.releaseCanvas = function () {
  82213. if (VirtualJoystick.vjCanvas) {
  82214. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  82215. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  82216. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  82217. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  82218. window.removeEventListener("resize", this._onResize);
  82219. document.body.removeChild(VirtualJoystick.vjCanvas);
  82220. VirtualJoystick.vjCanvas = null;
  82221. }
  82222. };
  82223. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  82224. VirtualJoystick._globalJoystickIndex = 0;
  82225. return VirtualJoystick;
  82226. }());
  82227. BABYLON.VirtualJoystick = VirtualJoystick;
  82228. })(BABYLON || (BABYLON = {}));
  82229. //# sourceMappingURL=babylon.virtualJoystick.js.map
  82230. var BABYLON;
  82231. (function (BABYLON) {
  82232. // We're mainly based on the logic defined into the FreeCamera code
  82233. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  82234. __extends(VirtualJoysticksCamera, _super);
  82235. function VirtualJoysticksCamera(name, position, scene) {
  82236. var _this = _super.call(this, name, position, scene) || this;
  82237. _this.inputs.addVirtualJoystick();
  82238. return _this;
  82239. }
  82240. VirtualJoysticksCamera.prototype.getClassName = function () {
  82241. return "VirtualJoysticksCamera";
  82242. };
  82243. return VirtualJoysticksCamera;
  82244. }(BABYLON.FreeCamera));
  82245. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  82246. })(BABYLON || (BABYLON = {}));
  82247. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  82248. var BABYLON;
  82249. (function (BABYLON) {
  82250. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  82251. function FreeCameraVirtualJoystickInput() {
  82252. }
  82253. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  82254. return this._leftjoystick;
  82255. };
  82256. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  82257. return this._rightjoystick;
  82258. };
  82259. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  82260. if (this._leftjoystick) {
  82261. var camera = this.camera;
  82262. var speed = camera._computeLocalCameraSpeed() * 50;
  82263. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  82264. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  82265. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  82266. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  82267. if (!this._leftjoystick.pressed) {
  82268. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  82269. }
  82270. if (!this._rightjoystick.pressed) {
  82271. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  82272. }
  82273. }
  82274. };
  82275. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  82276. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  82277. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  82278. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  82279. this._leftjoystick.setJoystickSensibility(0.15);
  82280. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  82281. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  82282. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  82283. this._rightjoystick.reverseUpDown = true;
  82284. this._rightjoystick.setJoystickSensibility(0.05);
  82285. this._rightjoystick.setJoystickColor("yellow");
  82286. };
  82287. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  82288. this._leftjoystick.releaseCanvas();
  82289. this._rightjoystick.releaseCanvas();
  82290. };
  82291. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  82292. return "FreeCameraVirtualJoystickInput";
  82293. };
  82294. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  82295. return "virtualJoystick";
  82296. };
  82297. return FreeCameraVirtualJoystickInput;
  82298. }());
  82299. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  82300. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  82301. })(BABYLON || (BABYLON = {}));
  82302. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  82303. var BABYLON;
  82304. (function (BABYLON) {
  82305. var SimplificationSettings = /** @class */ (function () {
  82306. function SimplificationSettings(quality, distance, optimizeMesh) {
  82307. this.quality = quality;
  82308. this.distance = distance;
  82309. this.optimizeMesh = optimizeMesh;
  82310. }
  82311. return SimplificationSettings;
  82312. }());
  82313. BABYLON.SimplificationSettings = SimplificationSettings;
  82314. var SimplificationQueue = /** @class */ (function () {
  82315. function SimplificationQueue() {
  82316. this.running = false;
  82317. this._simplificationArray = [];
  82318. }
  82319. SimplificationQueue.prototype.addTask = function (task) {
  82320. this._simplificationArray.push(task);
  82321. };
  82322. SimplificationQueue.prototype.executeNext = function () {
  82323. var task = this._simplificationArray.pop();
  82324. if (task) {
  82325. this.running = true;
  82326. this.runSimplification(task);
  82327. }
  82328. else {
  82329. this.running = false;
  82330. }
  82331. };
  82332. SimplificationQueue.prototype.runSimplification = function (task) {
  82333. var _this = this;
  82334. if (task.parallelProcessing) {
  82335. //parallel simplifier
  82336. task.settings.forEach(function (setting) {
  82337. var simplifier = _this.getSimplifier(task);
  82338. simplifier.simplify(setting, function (newMesh) {
  82339. task.mesh.addLODLevel(setting.distance, newMesh);
  82340. newMesh.isVisible = true;
  82341. //check if it is the last
  82342. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  82343. //all done, run the success callback.
  82344. task.successCallback();
  82345. }
  82346. _this.executeNext();
  82347. });
  82348. });
  82349. }
  82350. else {
  82351. //single simplifier.
  82352. var simplifier = this.getSimplifier(task);
  82353. var runDecimation = function (setting, callback) {
  82354. simplifier.simplify(setting, function (newMesh) {
  82355. task.mesh.addLODLevel(setting.distance, newMesh);
  82356. newMesh.isVisible = true;
  82357. //run the next quality level
  82358. callback();
  82359. });
  82360. };
  82361. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  82362. runDecimation(task.settings[loop.index], function () {
  82363. loop.executeNext();
  82364. });
  82365. }, function () {
  82366. //execution ended, run the success callback.
  82367. if (task.successCallback) {
  82368. task.successCallback();
  82369. }
  82370. _this.executeNext();
  82371. });
  82372. }
  82373. };
  82374. SimplificationQueue.prototype.getSimplifier = function (task) {
  82375. switch (task.simplificationType) {
  82376. case SimplificationType.QUADRATIC:
  82377. default:
  82378. return new QuadraticErrorSimplification(task.mesh);
  82379. }
  82380. };
  82381. return SimplificationQueue;
  82382. }());
  82383. BABYLON.SimplificationQueue = SimplificationQueue;
  82384. /**
  82385. * The implemented types of simplification.
  82386. * At the moment only Quadratic Error Decimation is implemented.
  82387. */
  82388. var SimplificationType;
  82389. (function (SimplificationType) {
  82390. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  82391. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  82392. var DecimationTriangle = /** @class */ (function () {
  82393. function DecimationTriangle(vertices) {
  82394. this.vertices = vertices;
  82395. this.error = new Array(4);
  82396. this.deleted = false;
  82397. this.isDirty = false;
  82398. this.deletePending = false;
  82399. this.borderFactor = 0;
  82400. }
  82401. return DecimationTriangle;
  82402. }());
  82403. BABYLON.DecimationTriangle = DecimationTriangle;
  82404. var DecimationVertex = /** @class */ (function () {
  82405. function DecimationVertex(position, id) {
  82406. this.position = position;
  82407. this.id = id;
  82408. this.isBorder = true;
  82409. this.q = new QuadraticMatrix();
  82410. this.triangleCount = 0;
  82411. this.triangleStart = 0;
  82412. this.originalOffsets = [];
  82413. }
  82414. DecimationVertex.prototype.updatePosition = function (newPosition) {
  82415. this.position.copyFrom(newPosition);
  82416. };
  82417. return DecimationVertex;
  82418. }());
  82419. BABYLON.DecimationVertex = DecimationVertex;
  82420. var QuadraticMatrix = /** @class */ (function () {
  82421. function QuadraticMatrix(data) {
  82422. this.data = new Array(10);
  82423. for (var i = 0; i < 10; ++i) {
  82424. if (data && data[i]) {
  82425. this.data[i] = data[i];
  82426. }
  82427. else {
  82428. this.data[i] = 0;
  82429. }
  82430. }
  82431. }
  82432. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  82433. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  82434. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  82435. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  82436. return det;
  82437. };
  82438. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  82439. for (var i = 0; i < 10; ++i) {
  82440. this.data[i] += matrix.data[i];
  82441. }
  82442. };
  82443. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  82444. for (var i = 0; i < 10; ++i) {
  82445. this.data[i] += data[i];
  82446. }
  82447. };
  82448. QuadraticMatrix.prototype.add = function (matrix) {
  82449. var m = new QuadraticMatrix();
  82450. for (var i = 0; i < 10; ++i) {
  82451. m.data[i] = this.data[i] + matrix.data[i];
  82452. }
  82453. return m;
  82454. };
  82455. QuadraticMatrix.FromData = function (a, b, c, d) {
  82456. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  82457. };
  82458. //returning an array to avoid garbage collection
  82459. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  82460. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  82461. };
  82462. return QuadraticMatrix;
  82463. }());
  82464. BABYLON.QuadraticMatrix = QuadraticMatrix;
  82465. var Reference = /** @class */ (function () {
  82466. function Reference(vertexId, triangleId) {
  82467. this.vertexId = vertexId;
  82468. this.triangleId = triangleId;
  82469. }
  82470. return Reference;
  82471. }());
  82472. BABYLON.Reference = Reference;
  82473. /**
  82474. * An implementation of the Quadratic Error simplification algorithm.
  82475. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  82476. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  82477. * @author RaananW
  82478. */
  82479. var QuadraticErrorSimplification = /** @class */ (function () {
  82480. function QuadraticErrorSimplification(_mesh) {
  82481. this._mesh = _mesh;
  82482. this.syncIterations = 5000;
  82483. this.aggressiveness = 7;
  82484. this.decimationIterations = 100;
  82485. this.boundingBoxEpsilon = BABYLON.Epsilon;
  82486. }
  82487. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  82488. var _this = this;
  82489. this.initDecimatedMesh();
  82490. //iterating through the submeshes array, one after the other.
  82491. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  82492. _this.initWithMesh(loop.index, function () {
  82493. _this.runDecimation(settings, loop.index, function () {
  82494. loop.executeNext();
  82495. });
  82496. }, settings.optimizeMesh);
  82497. }, function () {
  82498. setTimeout(function () {
  82499. successCallback(_this._reconstructedMesh);
  82500. }, 0);
  82501. });
  82502. };
  82503. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  82504. var _this = this;
  82505. var targetCount = ~~(this.triangles.length * settings.quality);
  82506. var deletedTriangles = 0;
  82507. var triangleCount = this.triangles.length;
  82508. var iterationFunction = function (iteration, callback) {
  82509. setTimeout(function () {
  82510. if (iteration % 5 === 0) {
  82511. _this.updateMesh(iteration === 0);
  82512. }
  82513. for (var i = 0; i < _this.triangles.length; ++i) {
  82514. _this.triangles[i].isDirty = false;
  82515. }
  82516. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  82517. var trianglesIterator = function (i) {
  82518. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  82519. var t = _this.triangles[tIdx];
  82520. if (!t)
  82521. return;
  82522. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  82523. return;
  82524. }
  82525. for (var j = 0; j < 3; ++j) {
  82526. if (t.error[j] < threshold) {
  82527. var deleted0 = [];
  82528. var deleted1 = [];
  82529. var v0 = t.vertices[j];
  82530. var v1 = t.vertices[(j + 1) % 3];
  82531. if (v0.isBorder || v1.isBorder)
  82532. continue;
  82533. var p = BABYLON.Vector3.Zero();
  82534. var n = BABYLON.Vector3.Zero();
  82535. var uv = BABYLON.Vector2.Zero();
  82536. var color = new BABYLON.Color4(0, 0, 0, 1);
  82537. _this.calculateError(v0, v1, p, n, uv, color);
  82538. var delTr = new Array();
  82539. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  82540. continue;
  82541. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  82542. continue;
  82543. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  82544. continue;
  82545. var uniqueArray = new Array();
  82546. delTr.forEach(function (deletedT) {
  82547. if (uniqueArray.indexOf(deletedT) === -1) {
  82548. deletedT.deletePending = true;
  82549. uniqueArray.push(deletedT);
  82550. }
  82551. });
  82552. if (uniqueArray.length % 2 !== 0) {
  82553. continue;
  82554. }
  82555. v0.q = v1.q.add(v0.q);
  82556. v0.updatePosition(p);
  82557. var tStart = _this.references.length;
  82558. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  82559. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  82560. var tCount = _this.references.length - tStart;
  82561. if (tCount <= v0.triangleCount) {
  82562. if (tCount) {
  82563. for (var c = 0; c < tCount; c++) {
  82564. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  82565. }
  82566. }
  82567. }
  82568. else {
  82569. v0.triangleStart = tStart;
  82570. }
  82571. v0.triangleCount = tCount;
  82572. break;
  82573. }
  82574. }
  82575. };
  82576. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  82577. }, 0);
  82578. };
  82579. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  82580. if (triangleCount - deletedTriangles <= targetCount)
  82581. loop.breakLoop();
  82582. else {
  82583. iterationFunction(loop.index, function () {
  82584. loop.executeNext();
  82585. });
  82586. }
  82587. }, function () {
  82588. setTimeout(function () {
  82589. //reconstruct this part of the mesh
  82590. _this.reconstructMesh(submeshIndex);
  82591. successCallback();
  82592. }, 0);
  82593. });
  82594. };
  82595. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  82596. var _this = this;
  82597. this.vertices = [];
  82598. this.triangles = [];
  82599. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  82600. var indices = this._mesh.getIndices();
  82601. var submesh = this._mesh.subMeshes[submeshIndex];
  82602. var findInVertices = function (positionToSearch) {
  82603. if (optimizeMesh) {
  82604. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  82605. if (_this.vertices[ii].position.equals(positionToSearch)) {
  82606. return _this.vertices[ii];
  82607. }
  82608. }
  82609. }
  82610. return null;
  82611. };
  82612. var vertexReferences = [];
  82613. var vertexInit = function (i) {
  82614. if (!positionData) {
  82615. return;
  82616. }
  82617. var offset = i + submesh.verticesStart;
  82618. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  82619. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  82620. vertex.originalOffsets.push(offset);
  82621. if (vertex.id === _this.vertices.length) {
  82622. _this.vertices.push(vertex);
  82623. }
  82624. vertexReferences.push(vertex.id);
  82625. };
  82626. //var totalVertices = mesh.getTotalVertices();
  82627. var totalVertices = submesh.verticesCount;
  82628. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  82629. var indicesInit = function (i) {
  82630. if (!indices) {
  82631. return;
  82632. }
  82633. var offset = (submesh.indexStart / 3) + i;
  82634. var pos = (offset * 3);
  82635. var i0 = indices[pos + 0];
  82636. var i1 = indices[pos + 1];
  82637. var i2 = indices[pos + 2];
  82638. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  82639. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  82640. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  82641. var triangle = new DecimationTriangle([v0, v1, v2]);
  82642. triangle.originalOffset = pos;
  82643. _this.triangles.push(triangle);
  82644. };
  82645. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  82646. _this.init(callback);
  82647. });
  82648. });
  82649. };
  82650. QuadraticErrorSimplification.prototype.init = function (callback) {
  82651. var _this = this;
  82652. var triangleInit1 = function (i) {
  82653. var t = _this.triangles[i];
  82654. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  82655. for (var j = 0; j < 3; j++) {
  82656. 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))));
  82657. }
  82658. };
  82659. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  82660. var triangleInit2 = function (i) {
  82661. var t = _this.triangles[i];
  82662. for (var j = 0; j < 3; ++j) {
  82663. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  82664. }
  82665. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  82666. };
  82667. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  82668. callback();
  82669. });
  82670. });
  82671. };
  82672. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  82673. var newTriangles = [];
  82674. var i;
  82675. for (i = 0; i < this.vertices.length; ++i) {
  82676. this.vertices[i].triangleCount = 0;
  82677. }
  82678. var t;
  82679. var j;
  82680. for (i = 0; i < this.triangles.length; ++i) {
  82681. if (!this.triangles[i].deleted) {
  82682. t = this.triangles[i];
  82683. for (j = 0; j < 3; ++j) {
  82684. t.vertices[j].triangleCount = 1;
  82685. }
  82686. newTriangles.push(t);
  82687. }
  82688. }
  82689. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  82690. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  82691. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  82692. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  82693. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  82694. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  82695. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  82696. var vertexCount = 0;
  82697. for (i = 0; i < this.vertices.length; ++i) {
  82698. var vertex = this.vertices[i];
  82699. vertex.id = vertexCount;
  82700. if (vertex.triangleCount) {
  82701. vertex.originalOffsets.forEach(function (originalOffset) {
  82702. if (!normalData) {
  82703. return;
  82704. }
  82705. newPositionData.push(vertex.position.x);
  82706. newPositionData.push(vertex.position.y);
  82707. newPositionData.push(vertex.position.z);
  82708. newNormalData.push(normalData[originalOffset * 3]);
  82709. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  82710. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  82711. if (uvs && uvs.length) {
  82712. newUVsData.push(uvs[(originalOffset * 2)]);
  82713. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  82714. }
  82715. else if (colorsData && colorsData.length) {
  82716. newColorsData.push(colorsData[(originalOffset * 4)]);
  82717. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  82718. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  82719. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  82720. }
  82721. ++vertexCount;
  82722. });
  82723. }
  82724. }
  82725. var startingIndex = this._reconstructedMesh.getTotalIndices();
  82726. var startingVertex = this._reconstructedMesh.getTotalVertices();
  82727. var submeshesArray = this._reconstructedMesh.subMeshes;
  82728. this._reconstructedMesh.subMeshes = [];
  82729. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  82730. var originalIndices = this._mesh.getIndices();
  82731. for (i = 0; i < newTriangles.length; ++i) {
  82732. t = newTriangles[i]; //now get the new referencing point for each vertex
  82733. [0, 1, 2].forEach(function (idx) {
  82734. var id = originalIndices[t.originalOffset + idx];
  82735. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  82736. if (offset < 0)
  82737. offset = 0;
  82738. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  82739. });
  82740. }
  82741. //overwriting the old vertex buffers and indices.
  82742. this._reconstructedMesh.setIndices(newIndicesArray);
  82743. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  82744. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  82745. if (newUVsData.length > 0)
  82746. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  82747. if (newColorsData.length > 0)
  82748. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  82749. //create submesh
  82750. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  82751. if (submeshIndex > 0) {
  82752. this._reconstructedMesh.subMeshes = [];
  82753. submeshesArray.forEach(function (submesh) {
  82754. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  82755. });
  82756. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  82757. }
  82758. };
  82759. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  82760. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  82761. this._reconstructedMesh.material = this._mesh.material;
  82762. this._reconstructedMesh.parent = this._mesh.parent;
  82763. this._reconstructedMesh.isVisible = false;
  82764. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  82765. };
  82766. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  82767. for (var i = 0; i < vertex1.triangleCount; ++i) {
  82768. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  82769. if (t.deleted)
  82770. continue;
  82771. var s = this.references[vertex1.triangleStart + i].vertexId;
  82772. var v1 = t.vertices[(s + 1) % 3];
  82773. var v2 = t.vertices[(s + 2) % 3];
  82774. if ((v1 === vertex2 || v2 === vertex2)) {
  82775. deletedArray[i] = true;
  82776. delTr.push(t);
  82777. continue;
  82778. }
  82779. var d1 = v1.position.subtract(point);
  82780. d1 = d1.normalize();
  82781. var d2 = v2.position.subtract(point);
  82782. d2 = d2.normalize();
  82783. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  82784. return true;
  82785. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  82786. deletedArray[i] = false;
  82787. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  82788. return true;
  82789. }
  82790. return false;
  82791. };
  82792. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  82793. var newDeleted = deletedTriangles;
  82794. for (var i = 0; i < vertex.triangleCount; ++i) {
  82795. var ref = this.references[vertex.triangleStart + i];
  82796. var t = this.triangles[ref.triangleId];
  82797. if (t.deleted)
  82798. continue;
  82799. if (deletedArray[i] && t.deletePending) {
  82800. t.deleted = true;
  82801. newDeleted++;
  82802. continue;
  82803. }
  82804. t.vertices[ref.vertexId] = origVertex;
  82805. t.isDirty = true;
  82806. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  82807. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  82808. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  82809. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  82810. this.references.push(ref);
  82811. }
  82812. return newDeleted;
  82813. };
  82814. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  82815. for (var i = 0; i < this.vertices.length; ++i) {
  82816. var vCount = [];
  82817. var vId = [];
  82818. var v = this.vertices[i];
  82819. var j;
  82820. for (j = 0; j < v.triangleCount; ++j) {
  82821. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  82822. for (var ii = 0; ii < 3; ii++) {
  82823. var ofs = 0;
  82824. var vv = triangle.vertices[ii];
  82825. while (ofs < vCount.length) {
  82826. if (vId[ofs] === vv.id)
  82827. break;
  82828. ++ofs;
  82829. }
  82830. if (ofs === vCount.length) {
  82831. vCount.push(1);
  82832. vId.push(vv.id);
  82833. }
  82834. else {
  82835. vCount[ofs]++;
  82836. }
  82837. }
  82838. }
  82839. for (j = 0; j < vCount.length; ++j) {
  82840. if (vCount[j] === 1) {
  82841. this.vertices[vId[j]].isBorder = true;
  82842. }
  82843. else {
  82844. this.vertices[vId[j]].isBorder = false;
  82845. }
  82846. }
  82847. }
  82848. };
  82849. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  82850. if (identifyBorders === void 0) { identifyBorders = false; }
  82851. var i;
  82852. if (!identifyBorders) {
  82853. var newTrianglesVector = [];
  82854. for (i = 0; i < this.triangles.length; ++i) {
  82855. if (!this.triangles[i].deleted) {
  82856. newTrianglesVector.push(this.triangles[i]);
  82857. }
  82858. }
  82859. this.triangles = newTrianglesVector;
  82860. }
  82861. for (i = 0; i < this.vertices.length; ++i) {
  82862. this.vertices[i].triangleCount = 0;
  82863. this.vertices[i].triangleStart = 0;
  82864. }
  82865. var t;
  82866. var j;
  82867. var v;
  82868. for (i = 0; i < this.triangles.length; ++i) {
  82869. t = this.triangles[i];
  82870. for (j = 0; j < 3; ++j) {
  82871. v = t.vertices[j];
  82872. v.triangleCount++;
  82873. }
  82874. }
  82875. var tStart = 0;
  82876. for (i = 0; i < this.vertices.length; ++i) {
  82877. this.vertices[i].triangleStart = tStart;
  82878. tStart += this.vertices[i].triangleCount;
  82879. this.vertices[i].triangleCount = 0;
  82880. }
  82881. var newReferences = new Array(this.triangles.length * 3);
  82882. for (i = 0; i < this.triangles.length; ++i) {
  82883. t = this.triangles[i];
  82884. for (j = 0; j < 3; ++j) {
  82885. v = t.vertices[j];
  82886. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  82887. v.triangleCount++;
  82888. }
  82889. }
  82890. this.references = newReferences;
  82891. if (identifyBorders) {
  82892. this.identifyBorder();
  82893. }
  82894. };
  82895. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  82896. var x = point.x;
  82897. var y = point.y;
  82898. var z = point.z;
  82899. 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
  82900. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  82901. };
  82902. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  82903. var q = vertex1.q.add(vertex2.q);
  82904. var border = vertex1.isBorder && vertex2.isBorder;
  82905. var error = 0;
  82906. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  82907. if (qDet !== 0 && !border) {
  82908. if (!pointResult) {
  82909. pointResult = BABYLON.Vector3.Zero();
  82910. }
  82911. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  82912. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  82913. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  82914. error = this.vertexError(q, pointResult);
  82915. }
  82916. else {
  82917. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  82918. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  82919. var error1 = this.vertexError(q, vertex1.position);
  82920. var error2 = this.vertexError(q, vertex2.position);
  82921. var error3 = this.vertexError(q, p3);
  82922. error = Math.min(error1, error2, error3);
  82923. if (error === error1) {
  82924. if (pointResult) {
  82925. pointResult.copyFrom(vertex1.position);
  82926. }
  82927. }
  82928. else if (error === error2) {
  82929. if (pointResult) {
  82930. pointResult.copyFrom(vertex2.position);
  82931. }
  82932. }
  82933. else {
  82934. if (pointResult) {
  82935. pointResult.copyFrom(p3);
  82936. }
  82937. }
  82938. }
  82939. return error;
  82940. };
  82941. return QuadraticErrorSimplification;
  82942. }());
  82943. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  82944. })(BABYLON || (BABYLON = {}));
  82945. //# sourceMappingURL=babylon.meshSimplification.js.map
  82946. var BABYLON;
  82947. (function (BABYLON) {
  82948. var MeshLODLevel = /** @class */ (function () {
  82949. function MeshLODLevel(distance, mesh) {
  82950. this.distance = distance;
  82951. this.mesh = mesh;
  82952. }
  82953. return MeshLODLevel;
  82954. }());
  82955. BABYLON.MeshLODLevel = MeshLODLevel;
  82956. })(BABYLON || (BABYLON = {}));
  82957. //# sourceMappingURL=babylon.meshLODLevel.js.map
  82958. var BABYLON;
  82959. (function (BABYLON) {
  82960. /**
  82961. * Defines the root class used to create scene optimization to use with SceneOptimizer
  82962. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82963. */
  82964. var SceneOptimization = /** @class */ (function () {
  82965. /**
  82966. * Creates the SceneOptimization object
  82967. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  82968. * @param desc defines the description associated with the optimization
  82969. */
  82970. function SceneOptimization(
  82971. /**
  82972. * Defines the priority of this optimization (0 by default which means first in the list)
  82973. */
  82974. priority) {
  82975. if (priority === void 0) { priority = 0; }
  82976. this.priority = priority;
  82977. }
  82978. /**
  82979. * Gets a string describing the action executed by the current optimization
  82980. * @returns description string
  82981. */
  82982. SceneOptimization.prototype.getDescription = function () {
  82983. return "";
  82984. };
  82985. /**
  82986. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82987. * @param scene defines the current scene where to apply this optimization
  82988. * @param optimizer defines the current optimizer
  82989. * @returns true if everything that can be done was applied
  82990. */
  82991. SceneOptimization.prototype.apply = function (scene, optimizer) {
  82992. return true;
  82993. };
  82994. ;
  82995. return SceneOptimization;
  82996. }());
  82997. BABYLON.SceneOptimization = SceneOptimization;
  82998. /**
  82999. * Defines an optimization used to reduce the size of render target textures
  83000. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83001. */
  83002. var TextureOptimization = /** @class */ (function (_super) {
  83003. __extends(TextureOptimization, _super);
  83004. /**
  83005. * Creates the TextureOptimization object
  83006. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83007. * @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
  83008. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  83009. */
  83010. function TextureOptimization(
  83011. /**
  83012. * Defines the priority of this optimization (0 by default which means first in the list)
  83013. */
  83014. priority,
  83015. /**
  83016. * 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
  83017. */
  83018. maximumSize,
  83019. /**
  83020. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  83021. */
  83022. step) {
  83023. if (priority === void 0) { priority = 0; }
  83024. if (maximumSize === void 0) { maximumSize = 1024; }
  83025. if (step === void 0) { step = 0.5; }
  83026. var _this = _super.call(this, priority) || this;
  83027. _this.priority = priority;
  83028. _this.maximumSize = maximumSize;
  83029. _this.step = step;
  83030. return _this;
  83031. }
  83032. /**
  83033. * Gets a string describing the action executed by the current optimization
  83034. * @returns description string
  83035. */
  83036. TextureOptimization.prototype.getDescription = function () {
  83037. return "Reducing render target texture size to " + this.maximumSize;
  83038. };
  83039. /**
  83040. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83041. * @param scene defines the current scene where to apply this optimization
  83042. * @param optimizer defines the current optimizer
  83043. * @returns true if everything that can be done was applied
  83044. */
  83045. TextureOptimization.prototype.apply = function (scene, optimizer) {
  83046. var allDone = true;
  83047. for (var index = 0; index < scene.textures.length; index++) {
  83048. var texture = scene.textures[index];
  83049. if (!texture.canRescale || texture.getContext) {
  83050. continue;
  83051. }
  83052. var currentSize = texture.getSize();
  83053. var maxDimension = Math.max(currentSize.width, currentSize.height);
  83054. if (maxDimension > this.maximumSize) {
  83055. texture.scale(this.step);
  83056. allDone = false;
  83057. }
  83058. }
  83059. return allDone;
  83060. };
  83061. return TextureOptimization;
  83062. }(SceneOptimization));
  83063. BABYLON.TextureOptimization = TextureOptimization;
  83064. /**
  83065. * Defines an optimization used to increase or decrease the rendering resolution
  83066. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83067. */
  83068. var HardwareScalingOptimization = /** @class */ (function (_super) {
  83069. __extends(HardwareScalingOptimization, _super);
  83070. /**
  83071. * Creates the HardwareScalingOptimization object
  83072. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83073. * @param maximumScale defines the maximum scale to use (2 by default)
  83074. * @param step defines the step to use between two passes (0.5 by default)
  83075. */
  83076. function HardwareScalingOptimization(
  83077. /**
  83078. * Defines the priority of this optimization (0 by default which means first in the list)
  83079. */
  83080. priority,
  83081. /**
  83082. * Defines the maximum scale to use (2 by default)
  83083. */
  83084. maximumScale,
  83085. /**
  83086. * Defines the step to use between two passes (0.5 by default)
  83087. */
  83088. step) {
  83089. if (priority === void 0) { priority = 0; }
  83090. if (maximumScale === void 0) { maximumScale = 2; }
  83091. if (step === void 0) { step = 0.25; }
  83092. var _this = _super.call(this, priority) || this;
  83093. _this.priority = priority;
  83094. _this.maximumScale = maximumScale;
  83095. _this.step = step;
  83096. _this._currentScale = -1;
  83097. _this._directionOffset = 1;
  83098. return _this;
  83099. }
  83100. /**
  83101. * Gets a string describing the action executed by the current optimization
  83102. * @return description string
  83103. */
  83104. HardwareScalingOptimization.prototype.getDescription = function () {
  83105. return "Setting hardware scaling level to " + this._currentScale;
  83106. };
  83107. /**
  83108. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83109. * @param scene defines the current scene where to apply this optimization
  83110. * @param optimizer defines the current optimizer
  83111. * @returns true if everything that can be done was applied
  83112. */
  83113. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  83114. if (this._currentScale === -1) {
  83115. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  83116. if (this._currentScale > this.maximumScale) {
  83117. this._directionOffset = -1;
  83118. }
  83119. }
  83120. this._currentScale += this._directionOffset * this.step;
  83121. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  83122. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  83123. };
  83124. ;
  83125. return HardwareScalingOptimization;
  83126. }(SceneOptimization));
  83127. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  83128. /**
  83129. * Defines an optimization used to remove shadows
  83130. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83131. */
  83132. var ShadowsOptimization = /** @class */ (function (_super) {
  83133. __extends(ShadowsOptimization, _super);
  83134. function ShadowsOptimization() {
  83135. return _super !== null && _super.apply(this, arguments) || this;
  83136. }
  83137. /**
  83138. * Gets a string describing the action executed by the current optimization
  83139. * @return description string
  83140. */
  83141. ShadowsOptimization.prototype.getDescription = function () {
  83142. return "Turning shadows on/off";
  83143. };
  83144. /**
  83145. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83146. * @param scene defines the current scene where to apply this optimization
  83147. * @param optimizer defines the current optimizer
  83148. * @returns true if everything that can be done was applied
  83149. */
  83150. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  83151. scene.shadowsEnabled = optimizer.isInImprovementMode;
  83152. return true;
  83153. };
  83154. ;
  83155. return ShadowsOptimization;
  83156. }(SceneOptimization));
  83157. BABYLON.ShadowsOptimization = ShadowsOptimization;
  83158. /**
  83159. * Defines an optimization used to turn post-processes off
  83160. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83161. */
  83162. var PostProcessesOptimization = /** @class */ (function (_super) {
  83163. __extends(PostProcessesOptimization, _super);
  83164. function PostProcessesOptimization() {
  83165. return _super !== null && _super.apply(this, arguments) || this;
  83166. }
  83167. /**
  83168. * Gets a string describing the action executed by the current optimization
  83169. * @return description string
  83170. */
  83171. PostProcessesOptimization.prototype.getDescription = function () {
  83172. return "Turning post-processes on/off";
  83173. };
  83174. /**
  83175. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83176. * @param scene defines the current scene where to apply this optimization
  83177. * @param optimizer defines the current optimizer
  83178. * @returns true if everything that can be done was applied
  83179. */
  83180. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  83181. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  83182. return true;
  83183. };
  83184. ;
  83185. return PostProcessesOptimization;
  83186. }(SceneOptimization));
  83187. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  83188. /**
  83189. * Defines an optimization used to turn lens flares off
  83190. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83191. */
  83192. var LensFlaresOptimization = /** @class */ (function (_super) {
  83193. __extends(LensFlaresOptimization, _super);
  83194. function LensFlaresOptimization() {
  83195. return _super !== null && _super.apply(this, arguments) || this;
  83196. }
  83197. /**
  83198. * Gets a string describing the action executed by the current optimization
  83199. * @return description string
  83200. */
  83201. LensFlaresOptimization.prototype.getDescription = function () {
  83202. return "Turning lens flares on/off";
  83203. };
  83204. /**
  83205. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83206. * @param scene defines the current scene where to apply this optimization
  83207. * @param optimizer defines the current optimizer
  83208. * @returns true if everything that can be done was applied
  83209. */
  83210. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  83211. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  83212. return true;
  83213. };
  83214. ;
  83215. return LensFlaresOptimization;
  83216. }(SceneOptimization));
  83217. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  83218. /**
  83219. * Defines an optimization based on user defined callback.
  83220. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83221. */
  83222. var CustomOptimization = /** @class */ (function (_super) {
  83223. __extends(CustomOptimization, _super);
  83224. function CustomOptimization() {
  83225. return _super !== null && _super.apply(this, arguments) || this;
  83226. }
  83227. /**
  83228. * Gets a string describing the action executed by the current optimization
  83229. * @returns description string
  83230. */
  83231. CustomOptimization.prototype.getDescription = function () {
  83232. if (this.onGetDescription) {
  83233. return this.onGetDescription();
  83234. }
  83235. return "Running user defined callback";
  83236. };
  83237. /**
  83238. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83239. * @param scene defines the current scene where to apply this optimization
  83240. * @param optimizer defines the current optimizer
  83241. * @returns true if everything that can be done was applied
  83242. */
  83243. CustomOptimization.prototype.apply = function (scene, optimizer) {
  83244. if (this.onApply) {
  83245. return this.onApply(scene, optimizer);
  83246. }
  83247. return true;
  83248. };
  83249. ;
  83250. return CustomOptimization;
  83251. }(SceneOptimization));
  83252. BABYLON.CustomOptimization = CustomOptimization;
  83253. /**
  83254. * Defines an optimization used to turn particles off
  83255. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83256. */
  83257. var ParticlesOptimization = /** @class */ (function (_super) {
  83258. __extends(ParticlesOptimization, _super);
  83259. function ParticlesOptimization() {
  83260. return _super !== null && _super.apply(this, arguments) || this;
  83261. }
  83262. /**
  83263. * Gets a string describing the action executed by the current optimization
  83264. * @return description string
  83265. */
  83266. ParticlesOptimization.prototype.getDescription = function () {
  83267. return "Turning particles on/off";
  83268. };
  83269. /**
  83270. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83271. * @param scene defines the current scene where to apply this optimization
  83272. * @param optimizer defines the current optimizer
  83273. * @returns true if everything that can be done was applied
  83274. */
  83275. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  83276. scene.particlesEnabled = optimizer.isInImprovementMode;
  83277. return true;
  83278. };
  83279. ;
  83280. return ParticlesOptimization;
  83281. }(SceneOptimization));
  83282. BABYLON.ParticlesOptimization = ParticlesOptimization;
  83283. /**
  83284. * Defines an optimization used to turn render targets off
  83285. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83286. */
  83287. var RenderTargetsOptimization = /** @class */ (function (_super) {
  83288. __extends(RenderTargetsOptimization, _super);
  83289. function RenderTargetsOptimization() {
  83290. return _super !== null && _super.apply(this, arguments) || this;
  83291. }
  83292. /**
  83293. * Gets a string describing the action executed by the current optimization
  83294. * @return description string
  83295. */
  83296. RenderTargetsOptimization.prototype.getDescription = function () {
  83297. return "Turning render targets off";
  83298. };
  83299. /**
  83300. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83301. * @param scene defines the current scene where to apply this optimization
  83302. * @param optimizer defines the current optimizer
  83303. * @returns true if everything that can be done was applied
  83304. */
  83305. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  83306. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  83307. return true;
  83308. };
  83309. ;
  83310. return RenderTargetsOptimization;
  83311. }(SceneOptimization));
  83312. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  83313. /**
  83314. * Defines an optimization used to merge meshes with compatible materials
  83315. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83316. */
  83317. var MergeMeshesOptimization = /** @class */ (function (_super) {
  83318. __extends(MergeMeshesOptimization, _super);
  83319. function MergeMeshesOptimization() {
  83320. var _this = _super !== null && _super.apply(this, arguments) || this;
  83321. _this._canBeMerged = function (abstractMesh) {
  83322. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  83323. return false;
  83324. }
  83325. var mesh = abstractMesh;
  83326. if (!mesh.isVisible || !mesh.isEnabled()) {
  83327. return false;
  83328. }
  83329. if (mesh.instances.length > 0) {
  83330. return false;
  83331. }
  83332. if (mesh.skeleton || mesh.hasLODLevels) {
  83333. return false;
  83334. }
  83335. if (mesh.parent) {
  83336. return false;
  83337. }
  83338. return true;
  83339. };
  83340. return _this;
  83341. }
  83342. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  83343. /**
  83344. * Gets or sets a boolean which defines if optimization octree has to be updated
  83345. */
  83346. get: function () {
  83347. return MergeMeshesOptimization._UpdateSelectionTree;
  83348. },
  83349. /**
  83350. * Gets or sets a boolean which defines if optimization octree has to be updated
  83351. */
  83352. set: function (value) {
  83353. MergeMeshesOptimization._UpdateSelectionTree = value;
  83354. },
  83355. enumerable: true,
  83356. configurable: true
  83357. });
  83358. /**
  83359. * Gets a string describing the action executed by the current optimization
  83360. * @return description string
  83361. */
  83362. MergeMeshesOptimization.prototype.getDescription = function () {
  83363. return "Merging similar meshes together";
  83364. };
  83365. /**
  83366. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83367. * @param scene defines the current scene where to apply this optimization
  83368. * @param optimizer defines the current optimizer
  83369. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  83370. * @returns true if everything that can be done was applied
  83371. */
  83372. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  83373. var globalPool = scene.meshes.slice(0);
  83374. var globalLength = globalPool.length;
  83375. for (var index = 0; index < globalLength; index++) {
  83376. var currentPool = new Array();
  83377. var current = globalPool[index];
  83378. // Checks
  83379. if (!this._canBeMerged(current)) {
  83380. continue;
  83381. }
  83382. currentPool.push(current);
  83383. // Find compatible meshes
  83384. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  83385. var otherMesh = globalPool[subIndex];
  83386. if (!this._canBeMerged(otherMesh)) {
  83387. continue;
  83388. }
  83389. if (otherMesh.material !== current.material) {
  83390. continue;
  83391. }
  83392. if (otherMesh.checkCollisions !== current.checkCollisions) {
  83393. continue;
  83394. }
  83395. currentPool.push(otherMesh);
  83396. globalLength--;
  83397. globalPool.splice(subIndex, 1);
  83398. subIndex--;
  83399. }
  83400. if (currentPool.length < 2) {
  83401. continue;
  83402. }
  83403. // Merge meshes
  83404. BABYLON.Mesh.MergeMeshes(currentPool);
  83405. }
  83406. if (updateSelectionTree != undefined) {
  83407. if (updateSelectionTree) {
  83408. scene.createOrUpdateSelectionOctree();
  83409. }
  83410. }
  83411. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  83412. scene.createOrUpdateSelectionOctree();
  83413. }
  83414. return true;
  83415. };
  83416. ;
  83417. MergeMeshesOptimization._UpdateSelectionTree = false;
  83418. return MergeMeshesOptimization;
  83419. }(SceneOptimization));
  83420. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  83421. /**
  83422. * Defines a list of options used by SceneOptimizer
  83423. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83424. */
  83425. var SceneOptimizerOptions = /** @class */ (function () {
  83426. /**
  83427. * Creates a new list of options used by SceneOptimizer
  83428. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  83429. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  83430. */
  83431. function SceneOptimizerOptions(
  83432. /**
  83433. * Defines the target frame rate to reach (60 by default)
  83434. */
  83435. targetFrameRate,
  83436. /**
  83437. * Defines the interval between two checkes (2000ms by default)
  83438. */
  83439. trackerDuration) {
  83440. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  83441. if (trackerDuration === void 0) { trackerDuration = 2000; }
  83442. this.targetFrameRate = targetFrameRate;
  83443. this.trackerDuration = trackerDuration;
  83444. /**
  83445. * Gets the list of optimizations to apply
  83446. */
  83447. this.optimizations = new Array();
  83448. }
  83449. /**
  83450. * Add a new optimization
  83451. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  83452. * @returns the current SceneOptimizerOptions
  83453. */
  83454. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  83455. this.optimizations.push(optimization);
  83456. return this;
  83457. };
  83458. /**
  83459. * Add a new custom optimization
  83460. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  83461. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  83462. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83463. * @returns the current SceneOptimizerOptions
  83464. */
  83465. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  83466. if (priority === void 0) { priority = 0; }
  83467. var optimization = new CustomOptimization(priority);
  83468. optimization.onApply = onApply;
  83469. optimization.onGetDescription = onGetDescription;
  83470. this.optimizations.push(optimization);
  83471. return this;
  83472. };
  83473. /**
  83474. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  83475. * @param targetFrameRate defines the target frame rate (60 by default)
  83476. * @returns a SceneOptimizerOptions object
  83477. */
  83478. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  83479. var result = new SceneOptimizerOptions(targetFrameRate);
  83480. var priority = 0;
  83481. result.addOptimization(new MergeMeshesOptimization(priority));
  83482. result.addOptimization(new ShadowsOptimization(priority));
  83483. result.addOptimization(new LensFlaresOptimization(priority));
  83484. // Next priority
  83485. priority++;
  83486. result.addOptimization(new PostProcessesOptimization(priority));
  83487. result.addOptimization(new ParticlesOptimization(priority));
  83488. // Next priority
  83489. priority++;
  83490. result.addOptimization(new TextureOptimization(priority, 1024));
  83491. return result;
  83492. };
  83493. /**
  83494. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  83495. * @param targetFrameRate defines the target frame rate (60 by default)
  83496. * @returns a SceneOptimizerOptions object
  83497. */
  83498. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  83499. var result = new SceneOptimizerOptions(targetFrameRate);
  83500. var priority = 0;
  83501. result.addOptimization(new MergeMeshesOptimization(priority));
  83502. result.addOptimization(new ShadowsOptimization(priority));
  83503. result.addOptimization(new LensFlaresOptimization(priority));
  83504. // Next priority
  83505. priority++;
  83506. result.addOptimization(new PostProcessesOptimization(priority));
  83507. result.addOptimization(new ParticlesOptimization(priority));
  83508. // Next priority
  83509. priority++;
  83510. result.addOptimization(new TextureOptimization(priority, 512));
  83511. // Next priority
  83512. priority++;
  83513. result.addOptimization(new RenderTargetsOptimization(priority));
  83514. // Next priority
  83515. priority++;
  83516. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  83517. return result;
  83518. };
  83519. /**
  83520. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  83521. * @param targetFrameRate defines the target frame rate (60 by default)
  83522. * @returns a SceneOptimizerOptions object
  83523. */
  83524. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  83525. var result = new SceneOptimizerOptions(targetFrameRate);
  83526. var priority = 0;
  83527. result.addOptimization(new MergeMeshesOptimization(priority));
  83528. result.addOptimization(new ShadowsOptimization(priority));
  83529. result.addOptimization(new LensFlaresOptimization(priority));
  83530. // Next priority
  83531. priority++;
  83532. result.addOptimization(new PostProcessesOptimization(priority));
  83533. result.addOptimization(new ParticlesOptimization(priority));
  83534. // Next priority
  83535. priority++;
  83536. result.addOptimization(new TextureOptimization(priority, 256));
  83537. // Next priority
  83538. priority++;
  83539. result.addOptimization(new RenderTargetsOptimization(priority));
  83540. // Next priority
  83541. priority++;
  83542. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  83543. return result;
  83544. };
  83545. return SceneOptimizerOptions;
  83546. }());
  83547. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  83548. /**
  83549. * Class used to run optimizations in order to reach a target frame rate
  83550. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83551. */
  83552. var SceneOptimizer = /** @class */ (function () {
  83553. /**
  83554. * Creates a new SceneOptimizer
  83555. * @param scene defines the scene to work on
  83556. * @param options defines the options to use with the SceneOptimizer
  83557. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  83558. * @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)
  83559. */
  83560. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  83561. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  83562. if (improvementMode === void 0) { improvementMode = false; }
  83563. var _this = this;
  83564. this._isRunning = false;
  83565. this._currentPriorityLevel = 0;
  83566. this._targetFrameRate = 60;
  83567. this._trackerDuration = 2000;
  83568. this._currentFrameRate = 0;
  83569. this._improvementMode = false;
  83570. /**
  83571. * Defines an observable called when the optimizer reaches the target frame rate
  83572. */
  83573. this.onSuccessObservable = new BABYLON.Observable();
  83574. /**
  83575. * Defines an observable called when the optimizer enables an optimization
  83576. */
  83577. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  83578. /**
  83579. * Defines an observable called when the optimizer is not able to reach the target frame rate
  83580. */
  83581. this.onFailureObservable = new BABYLON.Observable();
  83582. if (!options) {
  83583. this._options = new SceneOptimizerOptions();
  83584. }
  83585. else {
  83586. this._options = options;
  83587. }
  83588. if (this._options.targetFrameRate) {
  83589. this._targetFrameRate = this._options.targetFrameRate;
  83590. }
  83591. if (this._options.trackerDuration) {
  83592. this._trackerDuration = this._options.trackerDuration;
  83593. }
  83594. if (autoGeneratePriorities) {
  83595. var priority = 0;
  83596. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  83597. var optim = _a[_i];
  83598. optim.priority = priority++;
  83599. }
  83600. }
  83601. this._improvementMode = improvementMode;
  83602. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83603. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  83604. _this._sceneDisposeObserver = null;
  83605. _this.dispose();
  83606. });
  83607. }
  83608. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  83609. /**
  83610. * Gets a boolean indicating if the optimizer is in improvement mode
  83611. */
  83612. get: function () {
  83613. return this._improvementMode;
  83614. },
  83615. enumerable: true,
  83616. configurable: true
  83617. });
  83618. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  83619. /**
  83620. * Gets the current priority level (0 at start)
  83621. */
  83622. get: function () {
  83623. return this._currentPriorityLevel;
  83624. },
  83625. enumerable: true,
  83626. configurable: true
  83627. });
  83628. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  83629. /**
  83630. * Gets the current frame rate checked by the SceneOptimizer
  83631. */
  83632. get: function () {
  83633. return this._currentFrameRate;
  83634. },
  83635. enumerable: true,
  83636. configurable: true
  83637. });
  83638. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  83639. /**
  83640. * Gets or sets the current target frame rate (60 by default)
  83641. */
  83642. get: function () {
  83643. return this._targetFrameRate;
  83644. },
  83645. /**
  83646. * Gets or sets the current target frame rate (60 by default)
  83647. */
  83648. set: function (value) {
  83649. this._targetFrameRate = value;
  83650. },
  83651. enumerable: true,
  83652. configurable: true
  83653. });
  83654. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  83655. /**
  83656. * Gets or sets the current interval between two checks (every 2000ms by default)
  83657. */
  83658. get: function () {
  83659. return this._trackerDuration;
  83660. },
  83661. /**
  83662. * Gets or sets the current interval between two checks (every 2000ms by default)
  83663. */
  83664. set: function (value) {
  83665. this._trackerDuration = value;
  83666. },
  83667. enumerable: true,
  83668. configurable: true
  83669. });
  83670. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  83671. /**
  83672. * Gets the list of active optimizations
  83673. */
  83674. get: function () {
  83675. return this._options.optimizations;
  83676. },
  83677. enumerable: true,
  83678. configurable: true
  83679. });
  83680. /**
  83681. * Stops the current optimizer
  83682. */
  83683. SceneOptimizer.prototype.stop = function () {
  83684. this._isRunning = false;
  83685. };
  83686. /**
  83687. * Reset the optimizer to initial step (current priority level = 0)
  83688. */
  83689. SceneOptimizer.prototype.reset = function () {
  83690. this._currentPriorityLevel = 0;
  83691. };
  83692. /**
  83693. * Start the optimizer. By default it will try to reach a specific framerate
  83694. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  83695. */
  83696. SceneOptimizer.prototype.start = function () {
  83697. var _this = this;
  83698. if (this._isRunning) {
  83699. return;
  83700. }
  83701. this._isRunning = true;
  83702. // Let's wait for the scene to be ready before running our check
  83703. this._scene.executeWhenReady(function () {
  83704. setTimeout(function () {
  83705. _this._checkCurrentState();
  83706. }, _this._trackerDuration);
  83707. });
  83708. };
  83709. SceneOptimizer.prototype._checkCurrentState = function () {
  83710. var _this = this;
  83711. if (!this._isRunning) {
  83712. return;
  83713. }
  83714. var scene = this._scene;
  83715. var options = this._options;
  83716. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  83717. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  83718. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  83719. this._isRunning = false;
  83720. this.onSuccessObservable.notifyObservers(this);
  83721. return;
  83722. }
  83723. // Apply current level of optimizations
  83724. var allDone = true;
  83725. var noOptimizationApplied = true;
  83726. for (var index = 0; index < options.optimizations.length; index++) {
  83727. var optimization = options.optimizations[index];
  83728. if (optimization.priority === this._currentPriorityLevel) {
  83729. noOptimizationApplied = false;
  83730. allDone = allDone && optimization.apply(scene, this);
  83731. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  83732. }
  83733. }
  83734. // If no optimization was applied, this is a failure :(
  83735. if (noOptimizationApplied) {
  83736. this._isRunning = false;
  83737. this.onFailureObservable.notifyObservers(this);
  83738. return;
  83739. }
  83740. // If all optimizations were done, move to next level
  83741. if (allDone) {
  83742. this._currentPriorityLevel++;
  83743. }
  83744. // Let's the system running for a specific amount of time before checking FPS
  83745. scene.executeWhenReady(function () {
  83746. setTimeout(function () {
  83747. _this._checkCurrentState();
  83748. }, _this._trackerDuration);
  83749. });
  83750. };
  83751. /**
  83752. * Release all resources
  83753. */
  83754. SceneOptimizer.prototype.dispose = function () {
  83755. this.stop();
  83756. this.onSuccessObservable.clear();
  83757. this.onFailureObservable.clear();
  83758. this.onNewOptimizationAppliedObservable.clear();
  83759. if (this._sceneDisposeObserver) {
  83760. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  83761. }
  83762. };
  83763. /**
  83764. * Helper function to create a SceneOptimizer with one single line of code
  83765. * @param scene defines the scene to work on
  83766. * @param options defines the options to use with the SceneOptimizer
  83767. * @param onSuccess defines a callback to call on success
  83768. * @param onFailure defines a callback to call on failure
  83769. * @returns the new SceneOptimizer object
  83770. */
  83771. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  83772. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  83773. if (onSuccess) {
  83774. optimizer.onSuccessObservable.add(function () {
  83775. onSuccess();
  83776. });
  83777. }
  83778. if (onFailure) {
  83779. optimizer.onFailureObservable.add(function () {
  83780. onFailure();
  83781. });
  83782. }
  83783. optimizer.start();
  83784. return optimizer;
  83785. };
  83786. return SceneOptimizer;
  83787. }());
  83788. BABYLON.SceneOptimizer = SceneOptimizer;
  83789. })(BABYLON || (BABYLON = {}));
  83790. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  83791. var BABYLON;
  83792. (function (BABYLON) {
  83793. var OutlineRenderer = /** @class */ (function () {
  83794. function OutlineRenderer(scene) {
  83795. this.zOffset = 1;
  83796. this._scene = scene;
  83797. }
  83798. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  83799. var _this = this;
  83800. if (useOverlay === void 0) { useOverlay = false; }
  83801. var scene = this._scene;
  83802. var engine = this._scene.getEngine();
  83803. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  83804. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  83805. return;
  83806. }
  83807. var mesh = subMesh.getRenderingMesh();
  83808. var material = subMesh.getMaterial();
  83809. if (!material || !scene.activeCamera) {
  83810. return;
  83811. }
  83812. engine.enableEffect(this._effect);
  83813. // Logarithmic depth
  83814. if (material.useLogarithmicDepth) {
  83815. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  83816. }
  83817. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  83818. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  83819. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  83820. // Bones
  83821. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  83822. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  83823. }
  83824. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  83825. // Alpha test
  83826. if (material && material.needAlphaTesting()) {
  83827. var alphaTexture = material.getAlphaTestTexture();
  83828. if (alphaTexture) {
  83829. this._effect.setTexture("diffuseSampler", alphaTexture);
  83830. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  83831. }
  83832. }
  83833. engine.setZOffset(-this.zOffset);
  83834. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  83835. engine.setZOffset(0);
  83836. };
  83837. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  83838. var defines = [];
  83839. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  83840. var mesh = subMesh.getMesh();
  83841. var material = subMesh.getMaterial();
  83842. if (material) {
  83843. // Alpha test
  83844. if (material.needAlphaTesting()) {
  83845. defines.push("#define ALPHATEST");
  83846. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83847. attribs.push(BABYLON.VertexBuffer.UVKind);
  83848. defines.push("#define UV1");
  83849. }
  83850. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  83851. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83852. defines.push("#define UV2");
  83853. }
  83854. }
  83855. //Logarithmic depth
  83856. if (material.useLogarithmicDepth) {
  83857. defines.push("#define LOGARITHMICDEPTH");
  83858. }
  83859. }
  83860. // Bones
  83861. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83862. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83863. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83864. if (mesh.numBoneInfluencers > 4) {
  83865. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  83866. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  83867. }
  83868. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83869. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  83870. }
  83871. else {
  83872. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83873. }
  83874. // Instances
  83875. if (useInstances) {
  83876. defines.push("#define INSTANCES");
  83877. attribs.push("world0");
  83878. attribs.push("world1");
  83879. attribs.push("world2");
  83880. attribs.push("world3");
  83881. }
  83882. // Get correct effect
  83883. var join = defines.join("\n");
  83884. if (this._cachedDefines !== join) {
  83885. this._cachedDefines = join;
  83886. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  83887. }
  83888. return this._effect.isReady();
  83889. };
  83890. return OutlineRenderer;
  83891. }());
  83892. BABYLON.OutlineRenderer = OutlineRenderer;
  83893. })(BABYLON || (BABYLON = {}));
  83894. //# sourceMappingURL=babylon.outlineRenderer.js.map
  83895. var BABYLON;
  83896. (function (BABYLON) {
  83897. var FaceAdjacencies = /** @class */ (function () {
  83898. function FaceAdjacencies() {
  83899. this.edges = new Array();
  83900. this.edgesConnectedCount = 0;
  83901. }
  83902. return FaceAdjacencies;
  83903. }());
  83904. var EdgesRenderer = /** @class */ (function () {
  83905. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  83906. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  83907. if (epsilon === void 0) { epsilon = 0.95; }
  83908. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  83909. this.edgesWidthScalerForOrthographic = 1000.0;
  83910. this.edgesWidthScalerForPerspective = 50.0;
  83911. this._linesPositions = new Array();
  83912. this._linesNormals = new Array();
  83913. this._linesIndices = new Array();
  83914. this._buffers = {};
  83915. this._checkVerticesInsteadOfIndices = false;
  83916. this._source = source;
  83917. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  83918. this._epsilon = epsilon;
  83919. this._prepareRessources();
  83920. this._generateEdgesLines();
  83921. }
  83922. EdgesRenderer.prototype._prepareRessources = function () {
  83923. if (this._lineShader) {
  83924. return;
  83925. }
  83926. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  83927. attributes: ["position", "normal"],
  83928. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  83929. });
  83930. this._lineShader.disableDepthWrite = true;
  83931. this._lineShader.backFaceCulling = false;
  83932. };
  83933. EdgesRenderer.prototype._rebuild = function () {
  83934. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  83935. if (buffer) {
  83936. buffer._rebuild();
  83937. }
  83938. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  83939. if (buffer) {
  83940. buffer._rebuild();
  83941. }
  83942. var scene = this._source.getScene();
  83943. var engine = scene.getEngine();
  83944. this._ib = engine.createIndexBuffer(this._linesIndices);
  83945. };
  83946. EdgesRenderer.prototype.dispose = function () {
  83947. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  83948. if (buffer) {
  83949. buffer.dispose();
  83950. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  83951. }
  83952. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  83953. if (buffer) {
  83954. buffer.dispose();
  83955. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  83956. }
  83957. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  83958. this._lineShader.dispose();
  83959. };
  83960. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  83961. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  83962. return 0;
  83963. }
  83964. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  83965. return 1;
  83966. }
  83967. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  83968. return 2;
  83969. }
  83970. return -1;
  83971. };
  83972. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  83973. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  83974. return 0;
  83975. }
  83976. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  83977. return 1;
  83978. }
  83979. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  83980. return 2;
  83981. }
  83982. return -1;
  83983. };
  83984. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  83985. var needToCreateLine;
  83986. if (edge === undefined) {
  83987. needToCreateLine = true;
  83988. }
  83989. else {
  83990. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  83991. needToCreateLine = dotProduct < this._epsilon;
  83992. }
  83993. if (needToCreateLine) {
  83994. var offset = this._linesPositions.length / 3;
  83995. var normal = p0.subtract(p1);
  83996. normal.normalize();
  83997. // Positions
  83998. this._linesPositions.push(p0.x);
  83999. this._linesPositions.push(p0.y);
  84000. this._linesPositions.push(p0.z);
  84001. this._linesPositions.push(p0.x);
  84002. this._linesPositions.push(p0.y);
  84003. this._linesPositions.push(p0.z);
  84004. this._linesPositions.push(p1.x);
  84005. this._linesPositions.push(p1.y);
  84006. this._linesPositions.push(p1.z);
  84007. this._linesPositions.push(p1.x);
  84008. this._linesPositions.push(p1.y);
  84009. this._linesPositions.push(p1.z);
  84010. // Normals
  84011. this._linesNormals.push(p1.x);
  84012. this._linesNormals.push(p1.y);
  84013. this._linesNormals.push(p1.z);
  84014. this._linesNormals.push(-1);
  84015. this._linesNormals.push(p1.x);
  84016. this._linesNormals.push(p1.y);
  84017. this._linesNormals.push(p1.z);
  84018. this._linesNormals.push(1);
  84019. this._linesNormals.push(p0.x);
  84020. this._linesNormals.push(p0.y);
  84021. this._linesNormals.push(p0.z);
  84022. this._linesNormals.push(-1);
  84023. this._linesNormals.push(p0.x);
  84024. this._linesNormals.push(p0.y);
  84025. this._linesNormals.push(p0.z);
  84026. this._linesNormals.push(1);
  84027. // Indices
  84028. this._linesIndices.push(offset);
  84029. this._linesIndices.push(offset + 1);
  84030. this._linesIndices.push(offset + 2);
  84031. this._linesIndices.push(offset);
  84032. this._linesIndices.push(offset + 2);
  84033. this._linesIndices.push(offset + 3);
  84034. }
  84035. };
  84036. EdgesRenderer.prototype._generateEdgesLines = function () {
  84037. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  84038. var indices = this._source.getIndices();
  84039. if (!indices || !positions) {
  84040. return;
  84041. }
  84042. // First let's find adjacencies
  84043. var adjacencies = new Array();
  84044. var faceNormals = new Array();
  84045. var index;
  84046. var faceAdjacencies;
  84047. // Prepare faces
  84048. for (index = 0; index < indices.length; index += 3) {
  84049. faceAdjacencies = new FaceAdjacencies();
  84050. var p0Index = indices[index];
  84051. var p1Index = indices[index + 1];
  84052. var p2Index = indices[index + 2];
  84053. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  84054. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  84055. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  84056. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  84057. faceNormal.normalize();
  84058. faceNormals.push(faceNormal);
  84059. adjacencies.push(faceAdjacencies);
  84060. }
  84061. // Scan
  84062. for (index = 0; index < adjacencies.length; index++) {
  84063. faceAdjacencies = adjacencies[index];
  84064. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  84065. var otherFaceAdjacencies = adjacencies[otherIndex];
  84066. if (faceAdjacencies.edgesConnectedCount === 3) {
  84067. break;
  84068. }
  84069. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  84070. continue;
  84071. }
  84072. var otherP0 = indices[otherIndex * 3];
  84073. var otherP1 = indices[otherIndex * 3 + 1];
  84074. var otherP2 = indices[otherIndex * 3 + 2];
  84075. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  84076. var otherEdgeIndex = 0;
  84077. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  84078. continue;
  84079. }
  84080. switch (edgeIndex) {
  84081. case 0:
  84082. if (this._checkVerticesInsteadOfIndices) {
  84083. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  84084. }
  84085. else {
  84086. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  84087. }
  84088. break;
  84089. case 1:
  84090. if (this._checkVerticesInsteadOfIndices) {
  84091. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  84092. }
  84093. else {
  84094. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  84095. }
  84096. break;
  84097. case 2:
  84098. if (this._checkVerticesInsteadOfIndices) {
  84099. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  84100. }
  84101. else {
  84102. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  84103. }
  84104. break;
  84105. }
  84106. if (otherEdgeIndex === -1) {
  84107. continue;
  84108. }
  84109. faceAdjacencies.edges[edgeIndex] = otherIndex;
  84110. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  84111. faceAdjacencies.edgesConnectedCount++;
  84112. otherFaceAdjacencies.edgesConnectedCount++;
  84113. if (faceAdjacencies.edgesConnectedCount === 3) {
  84114. break;
  84115. }
  84116. }
  84117. }
  84118. }
  84119. // Create lines
  84120. for (index = 0; index < adjacencies.length; index++) {
  84121. // 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
  84122. var current = adjacencies[index];
  84123. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  84124. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  84125. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  84126. }
  84127. // Merge into a single mesh
  84128. var engine = this._source.getScene().getEngine();
  84129. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  84130. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  84131. this._ib = engine.createIndexBuffer(this._linesIndices);
  84132. this._indicesCount = this._linesIndices.length;
  84133. };
  84134. EdgesRenderer.prototype.render = function () {
  84135. var scene = this._source.getScene();
  84136. if (!this._lineShader.isReady() || !scene.activeCamera) {
  84137. return;
  84138. }
  84139. var engine = scene.getEngine();
  84140. this._lineShader._preBind();
  84141. // VBOs
  84142. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  84143. scene.resetCachedMaterial();
  84144. this._lineShader.setColor4("color", this._source.edgesColor);
  84145. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  84146. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  84147. }
  84148. else {
  84149. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  84150. }
  84151. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  84152. this._lineShader.bind(this._source.getWorldMatrix());
  84153. // Draw order
  84154. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  84155. this._lineShader.unbind();
  84156. engine.setDepthWrite(true);
  84157. };
  84158. return EdgesRenderer;
  84159. }());
  84160. BABYLON.EdgesRenderer = EdgesRenderer;
  84161. })(BABYLON || (BABYLON = {}));
  84162. //# sourceMappingURL=babylon.edgesRenderer.js.map
  84163. var __assign = (this && this.__assign) || Object.assign || function(t) {
  84164. for (var s, i = 1, n = arguments.length; i < n; i++) {
  84165. s = arguments[i];
  84166. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  84167. t[p] = s[p];
  84168. }
  84169. return t;
  84170. };
  84171. var BABYLON;
  84172. (function (BABYLON) {
  84173. /**
  84174. * The effect layer Helps adding post process effect blended with the main pass.
  84175. *
  84176. * This can be for instance use to generate glow or higlight effects on the scene.
  84177. *
  84178. * The effect layer class can not be used directly and is intented to inherited from to be
  84179. * customized per effects.
  84180. */
  84181. var EffectLayer = /** @class */ (function () {
  84182. /**
  84183. * Instantiates a new effect Layer and references it in the scene.
  84184. * @param name The name of the layer
  84185. * @param scene The scene to use the layer in
  84186. */
  84187. function EffectLayer(
  84188. /** The Friendly of the effect in the scene */
  84189. name, scene) {
  84190. this.name = name;
  84191. this._vertexBuffers = {};
  84192. this._maxSize = 0;
  84193. this._mainTextureDesiredSize = { width: 0, height: 0 };
  84194. this._shouldRender = true;
  84195. this._postProcesses = [];
  84196. this._textures = [];
  84197. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  84198. /**
  84199. * The clear color of the texture used to generate the glow map.
  84200. */
  84201. this.neutralColor = new BABYLON.Color4();
  84202. /**
  84203. * Specifies wether the highlight layer is enabled or not.
  84204. */
  84205. this.isEnabled = true;
  84206. /**
  84207. * An event triggered when the effect layer has been disposed.
  84208. */
  84209. this.onDisposeObservable = new BABYLON.Observable();
  84210. /**
  84211. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  84212. */
  84213. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  84214. /**
  84215. * An event triggered when the generated texture is being merged in the scene.
  84216. */
  84217. this.onBeforeComposeObservable = new BABYLON.Observable();
  84218. /**
  84219. * An event triggered when the generated texture has been merged in the scene.
  84220. */
  84221. this.onAfterComposeObservable = new BABYLON.Observable();
  84222. /**
  84223. * An event triggered when the efffect layer changes its size.
  84224. */
  84225. this.onSizeChangedObservable = new BABYLON.Observable();
  84226. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84227. this._engine = scene.getEngine();
  84228. this._maxSize = this._engine.getCaps().maxTextureSize;
  84229. this._scene.effectLayers.push(this);
  84230. // Generate Buffers
  84231. this._generateIndexBuffer();
  84232. this._genrateVertexBuffer();
  84233. }
  84234. Object.defineProperty(EffectLayer.prototype, "camera", {
  84235. /**
  84236. * Gets the camera attached to the layer.
  84237. */
  84238. get: function () {
  84239. return this._effectLayerOptions.camera;
  84240. },
  84241. enumerable: true,
  84242. configurable: true
  84243. });
  84244. /**
  84245. * Initializes the effect layer with the required options.
  84246. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  84247. */
  84248. EffectLayer.prototype._init = function (options) {
  84249. // Adapt options
  84250. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  84251. this._setMainTextureSize();
  84252. this._createMainTexture();
  84253. this._createTextureAndPostProcesses();
  84254. this._mergeEffect = this._createMergeEffect();
  84255. };
  84256. /**
  84257. * Generates the index buffer of the full screen quad blending to the main canvas.
  84258. */
  84259. EffectLayer.prototype._generateIndexBuffer = function () {
  84260. // Indices
  84261. var indices = [];
  84262. indices.push(0);
  84263. indices.push(1);
  84264. indices.push(2);
  84265. indices.push(0);
  84266. indices.push(2);
  84267. indices.push(3);
  84268. this._indexBuffer = this._engine.createIndexBuffer(indices);
  84269. };
  84270. /**
  84271. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  84272. */
  84273. EffectLayer.prototype._genrateVertexBuffer = function () {
  84274. // VBO
  84275. var vertices = [];
  84276. vertices.push(1, 1);
  84277. vertices.push(-1, 1);
  84278. vertices.push(-1, -1);
  84279. vertices.push(1, -1);
  84280. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  84281. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  84282. };
  84283. /**
  84284. * Sets the main texture desired size which is the closest power of two
  84285. * of the engine canvas size.
  84286. */
  84287. EffectLayer.prototype._setMainTextureSize = function () {
  84288. if (this._effectLayerOptions.mainTextureFixedSize) {
  84289. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  84290. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  84291. }
  84292. else {
  84293. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  84294. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  84295. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  84296. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  84297. }
  84298. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  84299. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  84300. };
  84301. /**
  84302. * Creates the main texture for the effect layer.
  84303. */
  84304. EffectLayer.prototype._createMainTexture = function () {
  84305. var _this = this;
  84306. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  84307. width: this._mainTextureDesiredSize.width,
  84308. height: this._mainTextureDesiredSize.height
  84309. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  84310. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  84311. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84312. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84313. this._mainTexture.anisotropicFilteringLevel = 1;
  84314. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84315. this._mainTexture.renderParticles = false;
  84316. this._mainTexture.renderList = null;
  84317. this._mainTexture.ignoreCameraViewport = true;
  84318. // Custom render function
  84319. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  84320. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  84321. var index;
  84322. var engine = _this._scene.getEngine();
  84323. if (depthOnlySubMeshes.length) {
  84324. engine.setColorWrite(false);
  84325. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  84326. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  84327. }
  84328. engine.setColorWrite(true);
  84329. }
  84330. for (index = 0; index < opaqueSubMeshes.length; index++) {
  84331. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  84332. }
  84333. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  84334. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  84335. }
  84336. for (index = 0; index < transparentSubMeshes.length; index++) {
  84337. _this._renderSubMesh(transparentSubMeshes.data[index]);
  84338. }
  84339. };
  84340. this._mainTexture.onClearObservable.add(function (engine) {
  84341. engine.clear(_this.neutralColor, true, true, true);
  84342. });
  84343. };
  84344. /**
  84345. * Checks for the readiness of the element composing the layer.
  84346. * @param subMesh the mesh to check for
  84347. * @param useInstances specify wether or not to use instances to render the mesh
  84348. * @param emissiveTexture the associated emissive texture used to generate the glow
  84349. * @return true if ready otherwise, false
  84350. */
  84351. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  84352. var material = subMesh.getMaterial();
  84353. if (!material) {
  84354. return false;
  84355. }
  84356. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  84357. return false;
  84358. }
  84359. var defines = [];
  84360. var attribs = [BABYLON.VertexBuffer.PositionKind];
  84361. var mesh = subMesh.getMesh();
  84362. var uv1 = false;
  84363. var uv2 = false;
  84364. // Alpha test
  84365. if (material && material.needAlphaTesting()) {
  84366. var alphaTexture = material.getAlphaTestTexture();
  84367. if (alphaTexture) {
  84368. defines.push("#define ALPHATEST");
  84369. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  84370. alphaTexture.coordinatesIndex === 1) {
  84371. defines.push("#define DIFFUSEUV2");
  84372. uv2 = true;
  84373. }
  84374. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84375. defines.push("#define DIFFUSEUV1");
  84376. uv1 = true;
  84377. }
  84378. }
  84379. }
  84380. // Emissive
  84381. if (emissiveTexture) {
  84382. defines.push("#define EMISSIVE");
  84383. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  84384. emissiveTexture.coordinatesIndex === 1) {
  84385. defines.push("#define EMISSIVEUV2");
  84386. uv2 = true;
  84387. }
  84388. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84389. defines.push("#define EMISSIVEUV1");
  84390. uv1 = true;
  84391. }
  84392. }
  84393. if (uv1) {
  84394. attribs.push(BABYLON.VertexBuffer.UVKind);
  84395. defines.push("#define UV1");
  84396. }
  84397. if (uv2) {
  84398. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  84399. defines.push("#define UV2");
  84400. }
  84401. // Bones
  84402. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  84403. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  84404. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  84405. if (mesh.numBoneInfluencers > 4) {
  84406. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  84407. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  84408. }
  84409. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  84410. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  84411. }
  84412. else {
  84413. defines.push("#define NUM_BONE_INFLUENCERS 0");
  84414. }
  84415. // Instances
  84416. if (useInstances) {
  84417. defines.push("#define INSTANCES");
  84418. attribs.push("world0");
  84419. attribs.push("world1");
  84420. attribs.push("world2");
  84421. attribs.push("world3");
  84422. }
  84423. // Get correct effect
  84424. var join = defines.join("\n");
  84425. if (this._cachedDefines !== join) {
  84426. this._cachedDefines = join;
  84427. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  84428. }
  84429. return this._effectLayerMapGenerationEffect.isReady();
  84430. };
  84431. /**
  84432. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  84433. */
  84434. EffectLayer.prototype.render = function () {
  84435. var currentEffect = this._mergeEffect;
  84436. // Check
  84437. if (!currentEffect.isReady())
  84438. return;
  84439. for (var i = 0; i < this._postProcesses.length; i++) {
  84440. if (!this._postProcesses[i].isReady()) {
  84441. return;
  84442. }
  84443. }
  84444. var engine = this._scene.getEngine();
  84445. this.onBeforeComposeObservable.notifyObservers(this);
  84446. // Render
  84447. engine.enableEffect(currentEffect);
  84448. engine.setState(false);
  84449. // VBOs
  84450. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  84451. // Cache
  84452. var previousAlphaMode = engine.getAlphaMode();
  84453. // Go Blend.
  84454. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  84455. // Blends the map on the main canvas.
  84456. this._internalRender(currentEffect);
  84457. // Restore Alpha
  84458. engine.setAlphaMode(previousAlphaMode);
  84459. this.onAfterComposeObservable.notifyObservers(this);
  84460. // Handle size changes.
  84461. var size = this._mainTexture.getSize();
  84462. this._setMainTextureSize();
  84463. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  84464. // Recreate RTT and post processes on size change.
  84465. this.onSizeChangedObservable.notifyObservers(this);
  84466. this._disposeTextureAndPostProcesses();
  84467. this._createMainTexture();
  84468. this._createTextureAndPostProcesses();
  84469. }
  84470. };
  84471. /**
  84472. * Determine if a given mesh will be used in the current effect.
  84473. * @param mesh mesh to test
  84474. * @returns true if the mesh will be used
  84475. */
  84476. EffectLayer.prototype.hasMesh = function (mesh) {
  84477. return true;
  84478. };
  84479. /**
  84480. * Returns true if the layer contains information to display, otherwise false.
  84481. * @returns true if the glow layer should be rendered
  84482. */
  84483. EffectLayer.prototype.shouldRender = function () {
  84484. return this.isEnabled && this._shouldRender;
  84485. };
  84486. /**
  84487. * Returns true if the mesh should render, otherwise false.
  84488. * @param mesh The mesh to render
  84489. * @returns true if it should render otherwise false
  84490. */
  84491. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  84492. return true;
  84493. };
  84494. /**
  84495. * Returns true if the mesh should render, otherwise false.
  84496. * @param mesh The mesh to render
  84497. * @returns true if it should render otherwise false
  84498. */
  84499. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  84500. return true;
  84501. };
  84502. /**
  84503. * Renders the submesh passed in parameter to the generation map.
  84504. */
  84505. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  84506. var _this = this;
  84507. if (!this.shouldRender()) {
  84508. return;
  84509. }
  84510. var material = subMesh.getMaterial();
  84511. var mesh = subMesh.getRenderingMesh();
  84512. var scene = this._scene;
  84513. var engine = scene.getEngine();
  84514. if (!material) {
  84515. return;
  84516. }
  84517. // Do not block in blend mode.
  84518. if (material.needAlphaBlendingForMesh(mesh)) {
  84519. return;
  84520. }
  84521. // Culling
  84522. engine.setState(material.backFaceCulling);
  84523. // Managing instances
  84524. var batch = mesh._getInstancesRenderList(subMesh._id);
  84525. if (batch.mustReturn) {
  84526. return;
  84527. }
  84528. // Early Exit per mesh
  84529. if (!this._shouldRenderMesh(mesh)) {
  84530. return;
  84531. }
  84532. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  84533. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  84534. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  84535. engine.enableEffect(this._effectLayerMapGenerationEffect);
  84536. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  84537. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  84538. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  84539. // Alpha test
  84540. if (material && material.needAlphaTesting()) {
  84541. var alphaTexture = material.getAlphaTestTexture();
  84542. if (alphaTexture) {
  84543. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  84544. var textureMatrix = alphaTexture.getTextureMatrix();
  84545. if (textureMatrix) {
  84546. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  84547. }
  84548. }
  84549. }
  84550. // Glow emissive only
  84551. if (this._emissiveTextureAndColor.texture) {
  84552. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  84553. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  84554. }
  84555. // Bones
  84556. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  84557. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  84558. }
  84559. // Draw
  84560. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  84561. }
  84562. else {
  84563. // Need to reset refresh rate of the shadowMap
  84564. this._mainTexture.resetRefreshCounter();
  84565. }
  84566. };
  84567. /**
  84568. * Rebuild the required buffers.
  84569. * @ignore Internal use only.
  84570. */
  84571. EffectLayer.prototype._rebuild = function () {
  84572. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84573. if (vb) {
  84574. vb._rebuild();
  84575. }
  84576. this._generateIndexBuffer();
  84577. };
  84578. /**
  84579. * Dispose only the render target textures and post process.
  84580. */
  84581. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  84582. this._mainTexture.dispose();
  84583. for (var i = 0; i < this._postProcesses.length; i++) {
  84584. if (this._postProcesses[i]) {
  84585. this._postProcesses[i].dispose();
  84586. }
  84587. }
  84588. this._postProcesses = [];
  84589. for (var i = 0; i < this._textures.length; i++) {
  84590. if (this._textures[i]) {
  84591. this._textures[i].dispose();
  84592. }
  84593. }
  84594. this._textures = [];
  84595. };
  84596. /**
  84597. * Dispose the highlight layer and free resources.
  84598. */
  84599. EffectLayer.prototype.dispose = function () {
  84600. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84601. if (vertexBuffer) {
  84602. vertexBuffer.dispose();
  84603. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84604. }
  84605. if (this._indexBuffer) {
  84606. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84607. this._indexBuffer = null;
  84608. }
  84609. // Clean textures and post processes
  84610. this._disposeTextureAndPostProcesses();
  84611. // Remove from scene
  84612. var index = this._scene.effectLayers.indexOf(this, 0);
  84613. if (index > -1) {
  84614. this._scene.effectLayers.splice(index, 1);
  84615. }
  84616. // Callback
  84617. this.onDisposeObservable.notifyObservers(this);
  84618. this.onDisposeObservable.clear();
  84619. this.onBeforeRenderMainTextureObservable.clear();
  84620. this.onBeforeComposeObservable.clear();
  84621. this.onAfterComposeObservable.clear();
  84622. this.onSizeChangedObservable.clear();
  84623. };
  84624. return EffectLayer;
  84625. }());
  84626. BABYLON.EffectLayer = EffectLayer;
  84627. })(BABYLON || (BABYLON = {}));
  84628. //# sourceMappingURL=babylon.effectLayer.js.map
  84629. var BABYLON;
  84630. (function (BABYLON) {
  84631. /**
  84632. * Special Glow Blur post process only blurring the alpha channel
  84633. * It enforces keeping the most luminous color in the color channel.
  84634. */
  84635. var GlowBlurPostProcess = /** @class */ (function (_super) {
  84636. __extends(GlowBlurPostProcess, _super);
  84637. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  84638. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  84639. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  84640. _this.direction = direction;
  84641. _this.kernel = kernel;
  84642. _this.onApplyObservable.add(function (effect) {
  84643. effect.setFloat2("screenSize", _this.width, _this.height);
  84644. effect.setVector2("direction", _this.direction);
  84645. effect.setFloat("blurWidth", _this.kernel);
  84646. });
  84647. return _this;
  84648. }
  84649. return GlowBlurPostProcess;
  84650. }(BABYLON.PostProcess));
  84651. /**
  84652. * The highlight layer Helps adding a glow effect around a mesh.
  84653. *
  84654. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  84655. * glowy meshes to your scene.
  84656. *
  84657. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  84658. */
  84659. var HighlightLayer = /** @class */ (function (_super) {
  84660. __extends(HighlightLayer, _super);
  84661. /**
  84662. * Instantiates a new highlight Layer and references it to the scene..
  84663. * @param name The name of the layer
  84664. * @param scene The scene to use the layer in
  84665. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  84666. */
  84667. function HighlightLayer(name, scene, options) {
  84668. var _this = _super.call(this, name, scene) || this;
  84669. _this.name = name;
  84670. /**
  84671. * Specifies whether or not the inner glow is ACTIVE in the layer.
  84672. */
  84673. _this.innerGlow = true;
  84674. /**
  84675. * Specifies whether or not the outer glow is ACTIVE in the layer.
  84676. */
  84677. _this.outerGlow = true;
  84678. /**
  84679. * An event triggered when the highlight layer is being blurred.
  84680. */
  84681. _this.onBeforeBlurObservable = new BABYLON.Observable();
  84682. /**
  84683. * An event triggered when the highlight layer has been blurred.
  84684. */
  84685. _this.onAfterBlurObservable = new BABYLON.Observable();
  84686. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  84687. _this._meshes = {};
  84688. _this._excludedMeshes = {};
  84689. _this.neutralColor = HighlightLayer.NeutralColor;
  84690. // Warn on stencil
  84691. if (!_this._engine.isStencilEnable) {
  84692. 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 }");
  84693. }
  84694. // Adapt options
  84695. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  84696. // Initialize the layer
  84697. _this._init({
  84698. alphaBlendingMode: _this._options.alphaBlendingMode,
  84699. camera: _this._options.camera,
  84700. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  84701. mainTextureRatio: _this._options.mainTextureRatio
  84702. });
  84703. // Do not render as long as no meshes have been added
  84704. _this._shouldRender = false;
  84705. return _this;
  84706. }
  84707. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  84708. /**
  84709. * Gets the horizontal size of the blur.
  84710. */
  84711. get: function () {
  84712. return this._horizontalBlurPostprocess.kernel;
  84713. },
  84714. /**
  84715. * Specifies the horizontal size of the blur.
  84716. */
  84717. set: function (value) {
  84718. this._horizontalBlurPostprocess.kernel = value;
  84719. },
  84720. enumerable: true,
  84721. configurable: true
  84722. });
  84723. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  84724. /**
  84725. * Gets the vertical size of the blur.
  84726. */
  84727. get: function () {
  84728. return this._verticalBlurPostprocess.kernel;
  84729. },
  84730. /**
  84731. * Specifies the vertical size of the blur.
  84732. */
  84733. set: function (value) {
  84734. this._verticalBlurPostprocess.kernel = value;
  84735. },
  84736. enumerable: true,
  84737. configurable: true
  84738. });
  84739. /**
  84740. * Get the effect name of the layer.
  84741. * @return The effect name
  84742. */
  84743. HighlightLayer.prototype.getEffectName = function () {
  84744. return HighlightLayer.EffectName;
  84745. };
  84746. /**
  84747. * Create the merge effect. This is the shader use to blit the information back
  84748. * to the main canvas at the end of the scene rendering.
  84749. */
  84750. HighlightLayer.prototype._createMergeEffect = function () {
  84751. // Effect
  84752. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  84753. };
  84754. /**
  84755. * Creates the render target textures and post processes used in the highlight layer.
  84756. */
  84757. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  84758. var _this = this;
  84759. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  84760. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  84761. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  84762. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  84763. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  84764. width: blurTextureWidth,
  84765. height: blurTextureHeight
  84766. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84767. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84768. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84769. this._blurTexture.anisotropicFilteringLevel = 16;
  84770. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  84771. this._blurTexture.renderParticles = false;
  84772. this._blurTexture.ignoreCameraViewport = true;
  84773. this._textures = [this._blurTexture];
  84774. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  84775. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  84776. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  84777. effect.setTexture("textureSampler", _this._mainTexture);
  84778. });
  84779. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  84780. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  84781. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  84782. });
  84783. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  84784. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  84785. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  84786. });
  84787. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  84788. }
  84789. else {
  84790. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  84791. width: blurTextureWidth,
  84792. height: blurTextureHeight
  84793. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84794. this._horizontalBlurPostprocess.width = blurTextureWidth;
  84795. this._horizontalBlurPostprocess.height = blurTextureHeight;
  84796. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  84797. effect.setTexture("textureSampler", _this._mainTexture);
  84798. });
  84799. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  84800. width: blurTextureWidth,
  84801. height: blurTextureHeight
  84802. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84803. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  84804. }
  84805. this._mainTexture.onAfterUnbindObservable.add(function () {
  84806. _this.onBeforeBlurObservable.notifyObservers(_this);
  84807. var internalTexture = _this._blurTexture.getInternalTexture();
  84808. if (internalTexture) {
  84809. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  84810. }
  84811. _this.onAfterBlurObservable.notifyObservers(_this);
  84812. });
  84813. // Prevent autoClear.
  84814. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  84815. };
  84816. /**
  84817. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  84818. */
  84819. HighlightLayer.prototype.needStencil = function () {
  84820. return true;
  84821. };
  84822. /**
  84823. * Checks for the readiness of the element composing the layer.
  84824. * @param subMesh the mesh to check for
  84825. * @param useInstances specify wether or not to use instances to render the mesh
  84826. * @param emissiveTexture the associated emissive texture used to generate the glow
  84827. * @return true if ready otherwise, false
  84828. */
  84829. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  84830. var material = subMesh.getMaterial();
  84831. var mesh = subMesh.getRenderingMesh();
  84832. if (!material || !mesh || !this._meshes) {
  84833. return false;
  84834. }
  84835. var emissiveTexture = null;
  84836. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  84837. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  84838. emissiveTexture = material.emissiveTexture;
  84839. }
  84840. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  84841. };
  84842. /**
  84843. * Implementation specific of rendering the generating effect on the main canvas.
  84844. * @param effect The effect used to render through
  84845. */
  84846. HighlightLayer.prototype._internalRender = function (effect) {
  84847. // Texture
  84848. effect.setTexture("textureSampler", this._blurTexture);
  84849. // Cache
  84850. var engine = this._engine;
  84851. var previousStencilBuffer = engine.getStencilBuffer();
  84852. var previousStencilFunction = engine.getStencilFunction();
  84853. var previousStencilMask = engine.getStencilMask();
  84854. var previousStencilOperationPass = engine.getStencilOperationPass();
  84855. var previousStencilOperationFail = engine.getStencilOperationFail();
  84856. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  84857. var previousStencilReference = engine.getStencilFunctionReference();
  84858. // Stencil operations
  84859. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  84860. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  84861. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  84862. // Draw order
  84863. engine.setStencilMask(0x00);
  84864. engine.setStencilBuffer(true);
  84865. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  84866. // 2 passes inner outer
  84867. if (this.outerGlow) {
  84868. effect.setFloat("offset", 0);
  84869. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  84870. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84871. }
  84872. if (this.innerGlow) {
  84873. effect.setFloat("offset", 1);
  84874. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  84875. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84876. }
  84877. // Restore Cache
  84878. engine.setStencilFunction(previousStencilFunction);
  84879. engine.setStencilMask(previousStencilMask);
  84880. engine.setStencilBuffer(previousStencilBuffer);
  84881. engine.setStencilOperationPass(previousStencilOperationPass);
  84882. engine.setStencilOperationFail(previousStencilOperationFail);
  84883. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  84884. engine.setStencilFunctionReference(previousStencilReference);
  84885. };
  84886. /**
  84887. * Returns true if the layer contains information to display, otherwise false.
  84888. */
  84889. HighlightLayer.prototype.shouldRender = function () {
  84890. if (_super.prototype.shouldRender.call(this)) {
  84891. return this._meshes ? true : false;
  84892. }
  84893. return false;
  84894. };
  84895. /**
  84896. * Returns true if the mesh should render, otherwise false.
  84897. * @param mesh The mesh to render
  84898. * @returns true if it should render otherwise false
  84899. */
  84900. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  84901. // Excluded Mesh
  84902. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  84903. return false;
  84904. }
  84905. ;
  84906. return true;
  84907. };
  84908. /**
  84909. * Sets the required values for both the emissive texture and and the main color.
  84910. */
  84911. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  84912. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  84913. if (highlightLayerMesh) {
  84914. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  84915. }
  84916. else {
  84917. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  84918. }
  84919. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  84920. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  84921. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  84922. }
  84923. else {
  84924. this._emissiveTextureAndColor.texture = null;
  84925. }
  84926. };
  84927. /**
  84928. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  84929. * @param mesh The mesh to exclude from the highlight layer
  84930. */
  84931. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  84932. if (!this._excludedMeshes) {
  84933. return;
  84934. }
  84935. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  84936. if (!meshExcluded) {
  84937. this._excludedMeshes[mesh.uniqueId] = {
  84938. mesh: mesh,
  84939. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  84940. mesh.getEngine().setStencilBuffer(false);
  84941. }),
  84942. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  84943. mesh.getEngine().setStencilBuffer(true);
  84944. }),
  84945. };
  84946. }
  84947. };
  84948. /**
  84949. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  84950. * @param mesh The mesh to highlight
  84951. */
  84952. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  84953. if (!this._excludedMeshes) {
  84954. return;
  84955. }
  84956. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  84957. if (meshExcluded) {
  84958. if (meshExcluded.beforeRender) {
  84959. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  84960. }
  84961. if (meshExcluded.afterRender) {
  84962. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  84963. }
  84964. }
  84965. this._excludedMeshes[mesh.uniqueId] = null;
  84966. };
  84967. /**
  84968. * Determine if a given mesh will be highlighted by the current HighlightLayer
  84969. * @param mesh mesh to test
  84970. * @returns true if the mesh will be highlighted by the current HighlightLayer
  84971. */
  84972. HighlightLayer.prototype.hasMesh = function (mesh) {
  84973. if (!this._meshes) {
  84974. return false;
  84975. }
  84976. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  84977. };
  84978. /**
  84979. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  84980. * @param mesh The mesh to highlight
  84981. * @param color The color of the highlight
  84982. * @param glowEmissiveOnly Extract the glow from the emissive texture
  84983. */
  84984. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  84985. var _this = this;
  84986. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  84987. if (!this._meshes) {
  84988. return;
  84989. }
  84990. var meshHighlight = this._meshes[mesh.uniqueId];
  84991. if (meshHighlight) {
  84992. meshHighlight.color = color;
  84993. }
  84994. else {
  84995. this._meshes[mesh.uniqueId] = {
  84996. mesh: mesh,
  84997. color: color,
  84998. // Lambda required for capture due to Observable this context
  84999. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  85000. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  85001. _this._defaultStencilReference(mesh);
  85002. }
  85003. else {
  85004. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  85005. }
  85006. }),
  85007. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  85008. glowEmissiveOnly: glowEmissiveOnly
  85009. };
  85010. }
  85011. this._shouldRender = true;
  85012. };
  85013. /**
  85014. * Remove a mesh from the highlight layer in order to make it stop glowing.
  85015. * @param mesh The mesh to highlight
  85016. */
  85017. HighlightLayer.prototype.removeMesh = function (mesh) {
  85018. if (!this._meshes) {
  85019. return;
  85020. }
  85021. var meshHighlight = this._meshes[mesh.uniqueId];
  85022. if (meshHighlight) {
  85023. if (meshHighlight.observerHighlight) {
  85024. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  85025. }
  85026. if (meshHighlight.observerDefault) {
  85027. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  85028. }
  85029. delete this._meshes[mesh.uniqueId];
  85030. }
  85031. this._shouldRender = false;
  85032. for (var meshHighlightToCheck in this._meshes) {
  85033. if (this._meshes[meshHighlightToCheck]) {
  85034. this._shouldRender = true;
  85035. break;
  85036. }
  85037. }
  85038. };
  85039. /**
  85040. * Force the stencil to the normal expected value for none glowing parts
  85041. */
  85042. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  85043. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  85044. };
  85045. /**
  85046. * Free any resources and references associated to a mesh.
  85047. * Internal use
  85048. * @param mesh The mesh to free.
  85049. */
  85050. HighlightLayer.prototype._disposeMesh = function (mesh) {
  85051. this.removeMesh(mesh);
  85052. this.removeExcludedMesh(mesh);
  85053. };
  85054. /**
  85055. * Dispose the highlight layer and free resources.
  85056. */
  85057. HighlightLayer.prototype.dispose = function () {
  85058. if (this._meshes) {
  85059. // Clean mesh references
  85060. for (var id in this._meshes) {
  85061. var meshHighlight = this._meshes[id];
  85062. if (meshHighlight && meshHighlight.mesh) {
  85063. if (meshHighlight.observerHighlight) {
  85064. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  85065. }
  85066. if (meshHighlight.observerDefault) {
  85067. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  85068. }
  85069. }
  85070. }
  85071. this._meshes = null;
  85072. }
  85073. if (this._excludedMeshes) {
  85074. for (var id in this._excludedMeshes) {
  85075. var meshHighlight = this._excludedMeshes[id];
  85076. if (meshHighlight) {
  85077. if (meshHighlight.beforeRender) {
  85078. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  85079. }
  85080. if (meshHighlight.afterRender) {
  85081. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  85082. }
  85083. }
  85084. }
  85085. this._excludedMeshes = null;
  85086. }
  85087. _super.prototype.dispose.call(this);
  85088. };
  85089. /**
  85090. * Effect Name of the highlight layer.
  85091. */
  85092. HighlightLayer.EffectName = "HighlightLayer";
  85093. /**
  85094. * The neutral color used during the preparation of the glow effect.
  85095. * This is black by default as the blend operation is a blend operation.
  85096. */
  85097. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  85098. /**
  85099. * Stencil value used for glowing meshes.
  85100. */
  85101. HighlightLayer.GlowingMeshStencilReference = 0x02;
  85102. /**
  85103. * Stencil value used for the other meshes in the scene.
  85104. */
  85105. HighlightLayer.NormalMeshStencilReference = 0x01;
  85106. return HighlightLayer;
  85107. }(BABYLON.EffectLayer));
  85108. BABYLON.HighlightLayer = HighlightLayer;
  85109. })(BABYLON || (BABYLON = {}));
  85110. //# sourceMappingURL=babylon.highlightLayer.js.map
  85111. var BABYLON;
  85112. (function (BABYLON) {
  85113. /**
  85114. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  85115. *
  85116. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  85117. * glowy meshes to your scene.
  85118. *
  85119. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  85120. */
  85121. var GlowLayer = /** @class */ (function (_super) {
  85122. __extends(GlowLayer, _super);
  85123. /**
  85124. * Instantiates a new glow Layer and references it to the scene.
  85125. * @param name The name of the layer
  85126. * @param scene The scene to use the layer in
  85127. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  85128. */
  85129. function GlowLayer(name, scene, options) {
  85130. var _this = _super.call(this, name, scene) || this;
  85131. _this.name = name;
  85132. _this._intensity = 1.0;
  85133. _this._includedOnlyMeshes = [];
  85134. _this._excludedMeshes = [];
  85135. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  85136. // Adapt options
  85137. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  85138. // Initialize the layer
  85139. _this._init({
  85140. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  85141. camera: _this._options.camera,
  85142. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  85143. mainTextureRatio: _this._options.mainTextureRatio
  85144. });
  85145. return _this;
  85146. }
  85147. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  85148. /**
  85149. * Gets the kernel size of the blur.
  85150. */
  85151. get: function () {
  85152. return this._horizontalBlurPostprocess1.kernel;
  85153. },
  85154. /**
  85155. * Sets the kernel size of the blur.
  85156. */
  85157. set: function (value) {
  85158. this._horizontalBlurPostprocess1.kernel = value;
  85159. this._verticalBlurPostprocess1.kernel = value;
  85160. this._horizontalBlurPostprocess2.kernel = value;
  85161. this._verticalBlurPostprocess2.kernel = value;
  85162. },
  85163. enumerable: true,
  85164. configurable: true
  85165. });
  85166. Object.defineProperty(GlowLayer.prototype, "intensity", {
  85167. /**
  85168. * Gets the glow intensity.
  85169. */
  85170. get: function () {
  85171. return this._intensity;
  85172. },
  85173. /**
  85174. * Sets the glow intensity.
  85175. */
  85176. set: function (value) {
  85177. this._intensity = value;
  85178. },
  85179. enumerable: true,
  85180. configurable: true
  85181. });
  85182. /**
  85183. * Get the effect name of the layer.
  85184. * @return The effect name
  85185. */
  85186. GlowLayer.prototype.getEffectName = function () {
  85187. return GlowLayer.EffectName;
  85188. };
  85189. /**
  85190. * Create the merge effect. This is the shader use to blit the information back
  85191. * to the main canvas at the end of the scene rendering.
  85192. */
  85193. GlowLayer.prototype._createMergeEffect = function () {
  85194. // Effect
  85195. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  85196. };
  85197. /**
  85198. * Creates the render target textures and post processes used in the glow layer.
  85199. */
  85200. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  85201. var _this = this;
  85202. var blurTextureWidth = this._mainTextureDesiredSize.width;
  85203. var blurTextureHeight = this._mainTextureDesiredSize.height;
  85204. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  85205. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  85206. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  85207. width: blurTextureWidth,
  85208. height: blurTextureHeight
  85209. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85210. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85211. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85212. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85213. this._blurTexture1.renderParticles = false;
  85214. this._blurTexture1.ignoreCameraViewport = true;
  85215. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  85216. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  85217. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  85218. width: blurTextureWidth2,
  85219. height: blurTextureHeight2
  85220. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85221. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85222. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85223. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85224. this._blurTexture2.renderParticles = false;
  85225. this._blurTexture2.ignoreCameraViewport = true;
  85226. this._textures = [this._blurTexture1, this._blurTexture2];
  85227. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  85228. width: blurTextureWidth,
  85229. height: blurTextureHeight
  85230. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85231. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  85232. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  85233. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  85234. effect.setTexture("textureSampler", _this._mainTexture);
  85235. });
  85236. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  85237. width: blurTextureWidth,
  85238. height: blurTextureHeight
  85239. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85240. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  85241. width: blurTextureWidth2,
  85242. height: blurTextureHeight2
  85243. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85244. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  85245. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  85246. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  85247. effect.setTexture("textureSampler", _this._blurTexture1);
  85248. });
  85249. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  85250. width: blurTextureWidth2,
  85251. height: blurTextureHeight2
  85252. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85253. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  85254. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  85255. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  85256. this._mainTexture.samples = this._options.mainTextureSamples;
  85257. this._mainTexture.onAfterUnbindObservable.add(function () {
  85258. var internalTexture = _this._blurTexture1.getInternalTexture();
  85259. if (internalTexture) {
  85260. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  85261. internalTexture = _this._blurTexture2.getInternalTexture();
  85262. if (internalTexture) {
  85263. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  85264. }
  85265. }
  85266. });
  85267. // Prevent autoClear.
  85268. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  85269. };
  85270. /**
  85271. * Checks for the readiness of the element composing the layer.
  85272. * @param subMesh the mesh to check for
  85273. * @param useInstances specify wether or not to use instances to render the mesh
  85274. * @param emissiveTexture the associated emissive texture used to generate the glow
  85275. * @return true if ready otherwise, false
  85276. */
  85277. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  85278. var material = subMesh.getMaterial();
  85279. var mesh = subMesh.getRenderingMesh();
  85280. if (!material || !mesh) {
  85281. return false;
  85282. }
  85283. var emissiveTexture = material.emissiveTexture;
  85284. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  85285. };
  85286. /**
  85287. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  85288. */
  85289. GlowLayer.prototype.needStencil = function () {
  85290. return false;
  85291. };
  85292. /**
  85293. * Implementation specific of rendering the generating effect on the main canvas.
  85294. * @param effect The effect used to render through
  85295. */
  85296. GlowLayer.prototype._internalRender = function (effect) {
  85297. // Texture
  85298. effect.setTexture("textureSampler", this._blurTexture1);
  85299. effect.setTexture("textureSampler2", this._blurTexture2);
  85300. effect.setFloat("offset", this._intensity);
  85301. // Cache
  85302. var engine = this._engine;
  85303. var previousStencilBuffer = engine.getStencilBuffer();
  85304. // Draw order
  85305. engine.setStencilBuffer(false);
  85306. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85307. // Draw order
  85308. engine.setStencilBuffer(previousStencilBuffer);
  85309. };
  85310. /**
  85311. * Sets the required values for both the emissive texture and and the main color.
  85312. */
  85313. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  85314. var textureLevel = 1.0;
  85315. if (this.customEmissiveTextureSelector) {
  85316. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  85317. }
  85318. else {
  85319. if (material) {
  85320. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  85321. if (this._emissiveTextureAndColor.texture) {
  85322. textureLevel = this._emissiveTextureAndColor.texture.level;
  85323. }
  85324. }
  85325. else {
  85326. this._emissiveTextureAndColor.texture = null;
  85327. }
  85328. }
  85329. if (this.customEmissiveColorSelector) {
  85330. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  85331. }
  85332. else {
  85333. if (material.emissiveColor) {
  85334. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  85335. }
  85336. else {
  85337. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  85338. }
  85339. }
  85340. };
  85341. /**
  85342. * Returns true if the mesh should render, otherwise false.
  85343. * @param mesh The mesh to render
  85344. * @returns true if it should render otherwise false
  85345. */
  85346. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  85347. return this.hasMesh(mesh);
  85348. };
  85349. /**
  85350. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  85351. * @param mesh The mesh to exclude from the glow layer
  85352. */
  85353. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  85354. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  85355. this._excludedMeshes.push(mesh.uniqueId);
  85356. }
  85357. };
  85358. /**
  85359. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  85360. * @param mesh The mesh to remove
  85361. */
  85362. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  85363. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  85364. if (index !== -1) {
  85365. this._excludedMeshes.splice(index, 1);
  85366. }
  85367. };
  85368. /**
  85369. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  85370. * @param mesh The mesh to include in the glow layer
  85371. */
  85372. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  85373. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  85374. this._includedOnlyMeshes.push(mesh.uniqueId);
  85375. }
  85376. };
  85377. /**
  85378. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  85379. * @param mesh The mesh to remove
  85380. */
  85381. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  85382. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  85383. if (index !== -1) {
  85384. this._includedOnlyMeshes.splice(index, 1);
  85385. }
  85386. };
  85387. /**
  85388. * Determine if a given mesh will be used in the glow layer
  85389. * @param mesh The mesh to test
  85390. * @returns true if the mesh will be highlighted by the current glow layer
  85391. */
  85392. GlowLayer.prototype.hasMesh = function (mesh) {
  85393. // Included Mesh
  85394. if (this._includedOnlyMeshes.length) {
  85395. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  85396. }
  85397. ;
  85398. // Excluded Mesh
  85399. if (this._excludedMeshes.length) {
  85400. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  85401. }
  85402. ;
  85403. return true;
  85404. };
  85405. /**
  85406. * Free any resources and references associated to a mesh.
  85407. * Internal use
  85408. * @param mesh The mesh to free.
  85409. */
  85410. GlowLayer.prototype._disposeMesh = function (mesh) {
  85411. this.removeIncludedOnlyMesh(mesh);
  85412. this.removeExcludedMesh(mesh);
  85413. };
  85414. /**
  85415. * Effect Name of the layer.
  85416. */
  85417. GlowLayer.EffectName = "GlowLayer";
  85418. /**
  85419. * The default blur kernel size used for the glow.
  85420. */
  85421. GlowLayer.DefaultBlurKernelSize = 32;
  85422. /**
  85423. * The default texture size ratio used for the glow.
  85424. */
  85425. GlowLayer.DefaultTextureRatio = 0.5;
  85426. return GlowLayer;
  85427. }(BABYLON.EffectLayer));
  85428. BABYLON.GlowLayer = GlowLayer;
  85429. })(BABYLON || (BABYLON = {}));
  85430. //# sourceMappingURL=babylon.glowLayer.js.map
  85431. var BABYLON;
  85432. (function (BABYLON) {
  85433. /**
  85434. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  85435. */
  85436. var AssetTaskState;
  85437. (function (AssetTaskState) {
  85438. /**
  85439. * Initialization
  85440. */
  85441. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  85442. /**
  85443. * Running
  85444. */
  85445. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  85446. /**
  85447. * Done
  85448. */
  85449. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  85450. /**
  85451. * Error
  85452. */
  85453. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  85454. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  85455. /**
  85456. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  85457. */
  85458. var AbstractAssetTask = /** @class */ (function () {
  85459. /**
  85460. * Creates a new {BABYLON.AssetsManager}
  85461. * @param name defines the name of the task
  85462. */
  85463. function AbstractAssetTask(
  85464. /**
  85465. * Task name
  85466. */ name) {
  85467. this.name = name;
  85468. this._isCompleted = false;
  85469. this._taskState = AssetTaskState.INIT;
  85470. }
  85471. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  85472. /**
  85473. * Get if the task is completed
  85474. */
  85475. get: function () {
  85476. return this._isCompleted;
  85477. },
  85478. enumerable: true,
  85479. configurable: true
  85480. });
  85481. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  85482. /**
  85483. * Gets the current state of the task
  85484. */
  85485. get: function () {
  85486. return this._taskState;
  85487. },
  85488. enumerable: true,
  85489. configurable: true
  85490. });
  85491. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  85492. /**
  85493. * Gets the current error object (if task is in error)
  85494. */
  85495. get: function () {
  85496. return this._errorObject;
  85497. },
  85498. enumerable: true,
  85499. configurable: true
  85500. });
  85501. /**
  85502. * Internal only
  85503. * @ignore
  85504. */
  85505. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  85506. if (this._errorObject) {
  85507. return;
  85508. }
  85509. this._errorObject = {
  85510. message: message,
  85511. exception: exception
  85512. };
  85513. };
  85514. /**
  85515. * Execute the current task
  85516. * @param scene defines the scene where you want your assets to be loaded
  85517. * @param onSuccess is a callback called when the task is successfully executed
  85518. * @param onError is a callback called if an error occurs
  85519. */
  85520. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  85521. var _this = this;
  85522. this._taskState = AssetTaskState.RUNNING;
  85523. this.runTask(scene, function () {
  85524. _this.onDoneCallback(onSuccess, onError);
  85525. }, function (msg, exception) {
  85526. _this.onErrorCallback(onError, msg, exception);
  85527. });
  85528. };
  85529. /**
  85530. * Execute the current task
  85531. * @param scene defines the scene where you want your assets to be loaded
  85532. * @param onSuccess is a callback called when the task is successfully executed
  85533. * @param onError is a callback called if an error occurs
  85534. */
  85535. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85536. throw new Error("runTask is not implemented");
  85537. };
  85538. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  85539. this._taskState = AssetTaskState.ERROR;
  85540. this._errorObject = {
  85541. message: message,
  85542. exception: exception
  85543. };
  85544. if (this.onError) {
  85545. this.onError(this, message, exception);
  85546. }
  85547. onError();
  85548. };
  85549. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  85550. try {
  85551. this._taskState = AssetTaskState.DONE;
  85552. this._isCompleted = true;
  85553. if (this.onSuccess) {
  85554. this.onSuccess(this);
  85555. }
  85556. onSuccess();
  85557. }
  85558. catch (e) {
  85559. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  85560. }
  85561. };
  85562. return AbstractAssetTask;
  85563. }());
  85564. BABYLON.AbstractAssetTask = AbstractAssetTask;
  85565. /**
  85566. * Class used to share progress information about assets loading
  85567. */
  85568. var AssetsProgressEvent = /** @class */ (function () {
  85569. /**
  85570. * Creates a {BABYLON.AssetsProgressEvent}
  85571. * @param remainingCount defines the number of remaining tasks to process
  85572. * @param totalCount defines the total number of tasks
  85573. * @param task defines the task that was just processed
  85574. */
  85575. function AssetsProgressEvent(remainingCount, totalCount, task) {
  85576. this.remainingCount = remainingCount;
  85577. this.totalCount = totalCount;
  85578. this.task = task;
  85579. }
  85580. return AssetsProgressEvent;
  85581. }());
  85582. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  85583. /**
  85584. * Define a task used by {BABYLON.AssetsManager} to load meshes
  85585. */
  85586. var MeshAssetTask = /** @class */ (function (_super) {
  85587. __extends(MeshAssetTask, _super);
  85588. /**
  85589. * Creates a new {BABYLON.MeshAssetTask}
  85590. * @param name defines the name of the task
  85591. * @param meshesNames defines the list of mesh's names you want to load
  85592. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  85593. * @param sceneFilename defines the filename of the scene to load from
  85594. */
  85595. function MeshAssetTask(
  85596. /**
  85597. * Defines the name of the task
  85598. */
  85599. name,
  85600. /**
  85601. * Defines the list of mesh's names you want to load
  85602. */
  85603. meshesNames,
  85604. /**
  85605. * Defines the root url to use as a base to load your meshes and associated resources
  85606. */
  85607. rootUrl,
  85608. /**
  85609. * Defines the filename of the scene to load from
  85610. */
  85611. sceneFilename) {
  85612. var _this = _super.call(this, name) || this;
  85613. _this.name = name;
  85614. _this.meshesNames = meshesNames;
  85615. _this.rootUrl = rootUrl;
  85616. _this.sceneFilename = sceneFilename;
  85617. return _this;
  85618. }
  85619. /**
  85620. * Execute the current task
  85621. * @param scene defines the scene where you want your assets to be loaded
  85622. * @param onSuccess is a callback called when the task is successfully executed
  85623. * @param onError is a callback called if an error occurs
  85624. */
  85625. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85626. var _this = this;
  85627. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  85628. _this.loadedMeshes = meshes;
  85629. _this.loadedParticleSystems = particleSystems;
  85630. _this.loadedSkeletons = skeletons;
  85631. onSuccess();
  85632. }, null, function (scene, message, exception) {
  85633. onError(message, exception);
  85634. });
  85635. };
  85636. return MeshAssetTask;
  85637. }(AbstractAssetTask));
  85638. BABYLON.MeshAssetTask = MeshAssetTask;
  85639. /**
  85640. * Define a task used by {BABYLON.AssetsManager} to load text content
  85641. */
  85642. var TextFileAssetTask = /** @class */ (function (_super) {
  85643. __extends(TextFileAssetTask, _super);
  85644. /**
  85645. * Creates a new TextFileAssetTask object
  85646. * @param name defines the name of the task
  85647. * @param url defines the location of the file to load
  85648. */
  85649. function TextFileAssetTask(
  85650. /**
  85651. * Defines the name of the task
  85652. */
  85653. name,
  85654. /**
  85655. * Defines the location of the file to load
  85656. */
  85657. url) {
  85658. var _this = _super.call(this, name) || this;
  85659. _this.name = name;
  85660. _this.url = url;
  85661. return _this;
  85662. }
  85663. /**
  85664. * Execute the current task
  85665. * @param scene defines the scene where you want your assets to be loaded
  85666. * @param onSuccess is a callback called when the task is successfully executed
  85667. * @param onError is a callback called if an error occurs
  85668. */
  85669. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85670. var _this = this;
  85671. scene._loadFile(this.url, function (data) {
  85672. _this.text = data;
  85673. onSuccess();
  85674. }, undefined, false, false, function (request, exception) {
  85675. if (request) {
  85676. onError(request.status + " " + request.statusText, exception);
  85677. }
  85678. });
  85679. };
  85680. return TextFileAssetTask;
  85681. }(AbstractAssetTask));
  85682. BABYLON.TextFileAssetTask = TextFileAssetTask;
  85683. /**
  85684. * Define a task used by {BABYLON.AssetsManager} to load binary data
  85685. */
  85686. var BinaryFileAssetTask = /** @class */ (function (_super) {
  85687. __extends(BinaryFileAssetTask, _super);
  85688. /**
  85689. * Creates a new BinaryFileAssetTask object
  85690. * @param name defines the name of the new task
  85691. * @param url defines the location of the file to load
  85692. */
  85693. function BinaryFileAssetTask(
  85694. /**
  85695. * Defines the name of the task
  85696. */
  85697. name,
  85698. /**
  85699. * Defines the location of the file to load
  85700. */
  85701. url) {
  85702. var _this = _super.call(this, name) || this;
  85703. _this.name = name;
  85704. _this.url = url;
  85705. return _this;
  85706. }
  85707. /**
  85708. * Execute the current task
  85709. * @param scene defines the scene where you want your assets to be loaded
  85710. * @param onSuccess is a callback called when the task is successfully executed
  85711. * @param onError is a callback called if an error occurs
  85712. */
  85713. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85714. var _this = this;
  85715. scene._loadFile(this.url, function (data) {
  85716. _this.data = data;
  85717. onSuccess();
  85718. }, undefined, true, true, function (request, exception) {
  85719. if (request) {
  85720. onError(request.status + " " + request.statusText, exception);
  85721. }
  85722. });
  85723. };
  85724. return BinaryFileAssetTask;
  85725. }(AbstractAssetTask));
  85726. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  85727. /**
  85728. * Define a task used by {BABYLON.AssetsManager} to load images
  85729. */
  85730. var ImageAssetTask = /** @class */ (function (_super) {
  85731. __extends(ImageAssetTask, _super);
  85732. /**
  85733. * Creates a new ImageAssetTask
  85734. * @param name defines the name of the task
  85735. * @param url defines the location of the image to load
  85736. */
  85737. function ImageAssetTask(
  85738. /**
  85739. * Defines the name of the task
  85740. */
  85741. name,
  85742. /**
  85743. * Defines the location of the image to load
  85744. */
  85745. url) {
  85746. var _this = _super.call(this, name) || this;
  85747. _this.name = name;
  85748. _this.url = url;
  85749. return _this;
  85750. }
  85751. /**
  85752. * Execute the current task
  85753. * @param scene defines the scene where you want your assets to be loaded
  85754. * @param onSuccess is a callback called when the task is successfully executed
  85755. * @param onError is a callback called if an error occurs
  85756. */
  85757. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85758. var _this = this;
  85759. var img = new Image();
  85760. BABYLON.Tools.SetCorsBehavior(this.url, img);
  85761. img.onload = function () {
  85762. _this.image = img;
  85763. onSuccess();
  85764. };
  85765. img.onerror = function (err) {
  85766. onError("Error loading image", err);
  85767. };
  85768. img.src = this.url;
  85769. };
  85770. return ImageAssetTask;
  85771. }(AbstractAssetTask));
  85772. BABYLON.ImageAssetTask = ImageAssetTask;
  85773. /**
  85774. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  85775. */
  85776. var TextureAssetTask = /** @class */ (function (_super) {
  85777. __extends(TextureAssetTask, _super);
  85778. /**
  85779. * Creates a new TextureAssetTask object
  85780. * @param name defines the name of the task
  85781. * @param url defines the location of the file to load
  85782. * @param noMipmap defines if mipmap should not be generated (default is false)
  85783. * @param invertY defines if texture must be inverted on Y axis (default is false)
  85784. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  85785. */
  85786. function TextureAssetTask(
  85787. /**
  85788. * Defines the name of the task
  85789. */
  85790. name,
  85791. /**
  85792. * Defines the location of the file to load
  85793. */
  85794. url,
  85795. /**
  85796. * Defines if mipmap should not be generated (default is false)
  85797. */
  85798. noMipmap,
  85799. /**
  85800. * Defines if texture must be inverted on Y axis (default is false)
  85801. */
  85802. invertY,
  85803. /**
  85804. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  85805. */
  85806. samplingMode) {
  85807. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  85808. var _this = _super.call(this, name) || this;
  85809. _this.name = name;
  85810. _this.url = url;
  85811. _this.noMipmap = noMipmap;
  85812. _this.invertY = invertY;
  85813. _this.samplingMode = samplingMode;
  85814. return _this;
  85815. }
  85816. /**
  85817. * Execute the current task
  85818. * @param scene defines the scene where you want your assets to be loaded
  85819. * @param onSuccess is a callback called when the task is successfully executed
  85820. * @param onError is a callback called if an error occurs
  85821. */
  85822. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85823. var onload = function () {
  85824. onSuccess();
  85825. };
  85826. var onerror = function (message, exception) {
  85827. onError(message, exception);
  85828. };
  85829. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  85830. };
  85831. return TextureAssetTask;
  85832. }(AbstractAssetTask));
  85833. BABYLON.TextureAssetTask = TextureAssetTask;
  85834. /**
  85835. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  85836. */
  85837. var CubeTextureAssetTask = /** @class */ (function (_super) {
  85838. __extends(CubeTextureAssetTask, _super);
  85839. /**
  85840. * Creates a new CubeTextureAssetTask
  85841. * @param name defines the name of the task
  85842. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  85843. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  85844. * @param noMipmap defines if mipmaps should not be generated (default is false)
  85845. * @param files defines the explicit list of files (undefined by default)
  85846. */
  85847. function CubeTextureAssetTask(
  85848. /**
  85849. * Defines the name of the task
  85850. */
  85851. name,
  85852. /**
  85853. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  85854. */
  85855. url,
  85856. /**
  85857. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  85858. */
  85859. extensions,
  85860. /**
  85861. * Defines if mipmaps should not be generated (default is false)
  85862. */
  85863. noMipmap,
  85864. /**
  85865. * Defines the explicit list of files (undefined by default)
  85866. */
  85867. files) {
  85868. var _this = _super.call(this, name) || this;
  85869. _this.name = name;
  85870. _this.url = url;
  85871. _this.extensions = extensions;
  85872. _this.noMipmap = noMipmap;
  85873. _this.files = files;
  85874. return _this;
  85875. }
  85876. /**
  85877. * Execute the current task
  85878. * @param scene defines the scene where you want your assets to be loaded
  85879. * @param onSuccess is a callback called when the task is successfully executed
  85880. * @param onError is a callback called if an error occurs
  85881. */
  85882. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85883. var onload = function () {
  85884. onSuccess();
  85885. };
  85886. var onerror = function (message, exception) {
  85887. onError(message, exception);
  85888. };
  85889. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  85890. };
  85891. return CubeTextureAssetTask;
  85892. }(AbstractAssetTask));
  85893. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  85894. /**
  85895. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  85896. */
  85897. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  85898. __extends(HDRCubeTextureAssetTask, _super);
  85899. /**
  85900. * Creates a new HDRCubeTextureAssetTask object
  85901. * @param name defines the name of the task
  85902. * @param url defines the location of the file to load
  85903. * @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.
  85904. * @param noMipmap defines if mipmaps should not be generated (default is false)
  85905. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  85906. * @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)
  85907. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  85908. */
  85909. function HDRCubeTextureAssetTask(
  85910. /**
  85911. * Defines the name of the task
  85912. */
  85913. name,
  85914. /**
  85915. * Defines the location of the file to load
  85916. */
  85917. url,
  85918. /**
  85919. * 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.
  85920. */
  85921. size,
  85922. /**
  85923. * Defines if mipmaps should not be generated (default is false)
  85924. */
  85925. noMipmap,
  85926. /**
  85927. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  85928. */
  85929. generateHarmonics,
  85930. /**
  85931. * 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)
  85932. */
  85933. useInGammaSpace,
  85934. /**
  85935. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  85936. */
  85937. usePMREMGenerator) {
  85938. if (noMipmap === void 0) { noMipmap = false; }
  85939. if (generateHarmonics === void 0) { generateHarmonics = true; }
  85940. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  85941. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  85942. var _this = _super.call(this, name) || this;
  85943. _this.name = name;
  85944. _this.url = url;
  85945. _this.size = size;
  85946. _this.noMipmap = noMipmap;
  85947. _this.generateHarmonics = generateHarmonics;
  85948. _this.useInGammaSpace = useInGammaSpace;
  85949. _this.usePMREMGenerator = usePMREMGenerator;
  85950. return _this;
  85951. }
  85952. /**
  85953. * Execute the current task
  85954. * @param scene defines the scene where you want your assets to be loaded
  85955. * @param onSuccess is a callback called when the task is successfully executed
  85956. * @param onError is a callback called if an error occurs
  85957. */
  85958. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  85959. var onload = function () {
  85960. onSuccess();
  85961. };
  85962. var onerror = function (message, exception) {
  85963. onError(message, exception);
  85964. };
  85965. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  85966. };
  85967. return HDRCubeTextureAssetTask;
  85968. }(AbstractAssetTask));
  85969. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  85970. /**
  85971. * This class can be used to easily import assets into a scene
  85972. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  85973. */
  85974. var AssetsManager = /** @class */ (function () {
  85975. /**
  85976. * Creates a new AssetsManager
  85977. * @param scene defines the scene to work on
  85978. */
  85979. function AssetsManager(scene) {
  85980. this._isLoading = false;
  85981. this._tasks = new Array();
  85982. this._waitingTasksCount = 0;
  85983. this._totalTasksCount = 0;
  85984. /**
  85985. * Observable called when all tasks are processed
  85986. */
  85987. this.onTaskSuccessObservable = new BABYLON.Observable();
  85988. /**
  85989. * Observable called when a task had an error
  85990. */
  85991. this.onTaskErrorObservable = new BABYLON.Observable();
  85992. /**
  85993. * Observable called when a task is successful
  85994. */
  85995. this.onTasksDoneObservable = new BABYLON.Observable();
  85996. /**
  85997. * Observable called when a task is done (whatever the result is)
  85998. */
  85999. this.onProgressObservable = new BABYLON.Observable();
  86000. /**
  86001. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  86002. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  86003. */
  86004. this.useDefaultLoadingScreen = true;
  86005. this._scene = scene;
  86006. }
  86007. /**
  86008. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  86009. * @param taskName defines the name of the new task
  86010. * @param meshesNames defines the name of meshes to load
  86011. * @param rootUrl defines the root url to use to locate files
  86012. * @param sceneFilename defines the filename of the scene file
  86013. * @returns a new {BABYLON.MeshAssetTask} object
  86014. */
  86015. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  86016. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  86017. this._tasks.push(task);
  86018. return task;
  86019. };
  86020. /**
  86021. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  86022. * @param taskName defines the name of the new task
  86023. * @param url defines the url of the file to load
  86024. * @returns a new {BABYLON.TextFileAssetTask} object
  86025. */
  86026. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  86027. var task = new TextFileAssetTask(taskName, url);
  86028. this._tasks.push(task);
  86029. return task;
  86030. };
  86031. /**
  86032. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  86033. * @param taskName defines the name of the new task
  86034. * @param url defines the url of the file to load
  86035. * @returns a new {BABYLON.BinaryFileAssetTask} object
  86036. */
  86037. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  86038. var task = new BinaryFileAssetTask(taskName, url);
  86039. this._tasks.push(task);
  86040. return task;
  86041. };
  86042. /**
  86043. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  86044. * @param taskName defines the name of the new task
  86045. * @param url defines the url of the file to load
  86046. * @returns a new {BABYLON.ImageAssetTask} object
  86047. */
  86048. AssetsManager.prototype.addImageTask = function (taskName, url) {
  86049. var task = new ImageAssetTask(taskName, url);
  86050. this._tasks.push(task);
  86051. return task;
  86052. };
  86053. /**
  86054. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  86055. * @param taskName defines the name of the new task
  86056. * @param url defines the url of the file to load
  86057. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  86058. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  86059. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  86060. * @returns a new {BABYLON.TextureAssetTask} object
  86061. */
  86062. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  86063. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  86064. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  86065. this._tasks.push(task);
  86066. return task;
  86067. };
  86068. /**
  86069. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  86070. * @param taskName defines the name of the new task
  86071. * @param url defines the url of the file to load
  86072. * @param extensions defines the extension to use to load the cube map (can be null)
  86073. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  86074. * @param files defines the list of files to load (can be null)
  86075. * @returns a new {BABYLON.CubeTextureAssetTask} object
  86076. */
  86077. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  86078. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  86079. this._tasks.push(task);
  86080. return task;
  86081. };
  86082. /**
  86083. *
  86084. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  86085. * @param taskName defines the name of the new task
  86086. * @param url defines the url of the file to load
  86087. * @param size defines the size you want for the cubemap (can be null)
  86088. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  86089. * @param generateHarmonics defines if you want to automatically generate (true by default)
  86090. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  86091. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  86092. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  86093. */
  86094. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  86095. if (noMipmap === void 0) { noMipmap = false; }
  86096. if (generateHarmonics === void 0) { generateHarmonics = true; }
  86097. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  86098. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  86099. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  86100. this._tasks.push(task);
  86101. return task;
  86102. };
  86103. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  86104. var _this = this;
  86105. this._waitingTasksCount--;
  86106. try {
  86107. if (task.taskState === AssetTaskState.DONE) {
  86108. // Let's remove successfull tasks
  86109. BABYLON.Tools.SetImmediate(function () {
  86110. var index = _this._tasks.indexOf(task);
  86111. if (index > -1) {
  86112. _this._tasks.splice(index, 1);
  86113. }
  86114. });
  86115. }
  86116. if (this.onProgress) {
  86117. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  86118. }
  86119. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  86120. }
  86121. catch (e) {
  86122. BABYLON.Tools.Error("Error running progress callbacks.");
  86123. console.log(e);
  86124. }
  86125. if (this._waitingTasksCount === 0) {
  86126. try {
  86127. if (this.onFinish) {
  86128. this.onFinish(this._tasks);
  86129. }
  86130. this.onTasksDoneObservable.notifyObservers(this._tasks);
  86131. }
  86132. catch (e) {
  86133. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  86134. console.log(e);
  86135. }
  86136. this._isLoading = false;
  86137. this._scene.getEngine().hideLoadingUI();
  86138. }
  86139. };
  86140. AssetsManager.prototype._runTask = function (task) {
  86141. var _this = this;
  86142. var done = function () {
  86143. try {
  86144. if (_this.onTaskSuccess) {
  86145. _this.onTaskSuccess(task);
  86146. }
  86147. _this.onTaskSuccessObservable.notifyObservers(task);
  86148. _this._decreaseWaitingTasksCount(task);
  86149. }
  86150. catch (e) {
  86151. error("Error executing task success callbacks", e);
  86152. }
  86153. };
  86154. var error = function (message, exception) {
  86155. task._setErrorObject(message, exception);
  86156. if (_this.onTaskError) {
  86157. _this.onTaskError(task);
  86158. }
  86159. _this.onTaskErrorObservable.notifyObservers(task);
  86160. _this._decreaseWaitingTasksCount(task);
  86161. };
  86162. task.run(this._scene, done, error);
  86163. };
  86164. /**
  86165. * Reset the {BABYLON.AssetsManager} and remove all tasks
  86166. * @return the current instance of the {BABYLON.AssetsManager}
  86167. */
  86168. AssetsManager.prototype.reset = function () {
  86169. this._isLoading = false;
  86170. this._tasks = new Array();
  86171. return this;
  86172. };
  86173. /**
  86174. * Start the loading process
  86175. * @return the current instance of the {BABYLON.AssetsManager}
  86176. */
  86177. AssetsManager.prototype.load = function () {
  86178. if (this._isLoading) {
  86179. return this;
  86180. }
  86181. this._isLoading = true;
  86182. this._waitingTasksCount = this._tasks.length;
  86183. this._totalTasksCount = this._tasks.length;
  86184. if (this._waitingTasksCount === 0) {
  86185. this._isLoading = false;
  86186. if (this.onFinish) {
  86187. this.onFinish(this._tasks);
  86188. }
  86189. this.onTasksDoneObservable.notifyObservers(this._tasks);
  86190. return this;
  86191. }
  86192. if (this.useDefaultLoadingScreen) {
  86193. this._scene.getEngine().displayLoadingUI();
  86194. }
  86195. for (var index = 0; index < this._tasks.length; index++) {
  86196. var task = this._tasks[index];
  86197. this._runTask(task);
  86198. }
  86199. return this;
  86200. };
  86201. return AssetsManager;
  86202. }());
  86203. BABYLON.AssetsManager = AssetsManager;
  86204. })(BABYLON || (BABYLON = {}));
  86205. //# sourceMappingURL=babylon.assetsManager.js.map
  86206. var BABYLON;
  86207. (function (BABYLON) {
  86208. var serializedGeometries = [];
  86209. var serializeGeometry = function (geometry, serializationGeometries) {
  86210. if (serializedGeometries[geometry.id]) {
  86211. return;
  86212. }
  86213. if (geometry.doNotSerialize) {
  86214. return;
  86215. }
  86216. if (geometry instanceof BABYLON.BoxGeometry) {
  86217. serializationGeometries.boxes.push(geometry.serialize());
  86218. }
  86219. else if (geometry instanceof BABYLON.SphereGeometry) {
  86220. serializationGeometries.spheres.push(geometry.serialize());
  86221. }
  86222. else if (geometry instanceof BABYLON.CylinderGeometry) {
  86223. serializationGeometries.cylinders.push(geometry.serialize());
  86224. }
  86225. else if (geometry instanceof BABYLON.TorusGeometry) {
  86226. serializationGeometries.toruses.push(geometry.serialize());
  86227. }
  86228. else if (geometry instanceof BABYLON.GroundGeometry) {
  86229. serializationGeometries.grounds.push(geometry.serialize());
  86230. }
  86231. else if (geometry instanceof BABYLON.Plane) {
  86232. serializationGeometries.planes.push(geometry.serialize());
  86233. }
  86234. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  86235. serializationGeometries.torusKnots.push(geometry.serialize());
  86236. }
  86237. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  86238. throw new Error("Unknown primitive type");
  86239. }
  86240. else {
  86241. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  86242. }
  86243. serializedGeometries[geometry.id] = true;
  86244. };
  86245. var serializeMesh = function (mesh, serializationScene) {
  86246. var serializationObject = {};
  86247. // Geometry
  86248. var geometry = mesh._geometry;
  86249. if (geometry) {
  86250. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  86251. // 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
  86252. serializeGeometry(geometry, serializationScene.geometries);
  86253. }
  86254. }
  86255. // Custom
  86256. if (mesh.serialize) {
  86257. mesh.serialize(serializationObject);
  86258. }
  86259. return serializationObject;
  86260. };
  86261. var finalizeSingleMesh = function (mesh, serializationObject) {
  86262. //only works if the mesh is already loaded
  86263. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  86264. //serialize material
  86265. if (mesh.material) {
  86266. if (mesh.material instanceof BABYLON.StandardMaterial) {
  86267. serializationObject.materials = serializationObject.materials || [];
  86268. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  86269. serializationObject.materials.push(mesh.material.serialize());
  86270. }
  86271. }
  86272. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  86273. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  86274. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  86275. serializationObject.multiMaterials.push(mesh.material.serialize());
  86276. }
  86277. }
  86278. }
  86279. //serialize geometry
  86280. var geometry = mesh._geometry;
  86281. if (geometry) {
  86282. if (!serializationObject.geometries) {
  86283. serializationObject.geometries = {};
  86284. serializationObject.geometries.boxes = [];
  86285. serializationObject.geometries.spheres = [];
  86286. serializationObject.geometries.cylinders = [];
  86287. serializationObject.geometries.toruses = [];
  86288. serializationObject.geometries.grounds = [];
  86289. serializationObject.geometries.planes = [];
  86290. serializationObject.geometries.torusKnots = [];
  86291. serializationObject.geometries.vertexData = [];
  86292. }
  86293. serializeGeometry(geometry, serializationObject.geometries);
  86294. }
  86295. // Skeletons
  86296. if (mesh.skeleton) {
  86297. serializationObject.skeletons = serializationObject.skeletons || [];
  86298. serializationObject.skeletons.push(mesh.skeleton.serialize());
  86299. }
  86300. //serialize the actual mesh
  86301. serializationObject.meshes = serializationObject.meshes || [];
  86302. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  86303. }
  86304. };
  86305. var SceneSerializer = /** @class */ (function () {
  86306. function SceneSerializer() {
  86307. }
  86308. SceneSerializer.ClearCache = function () {
  86309. serializedGeometries = [];
  86310. };
  86311. SceneSerializer.Serialize = function (scene) {
  86312. var serializationObject = {};
  86313. SceneSerializer.ClearCache();
  86314. // Scene
  86315. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  86316. serializationObject.autoClear = scene.autoClear;
  86317. serializationObject.clearColor = scene.clearColor.asArray();
  86318. serializationObject.ambientColor = scene.ambientColor.asArray();
  86319. serializationObject.gravity = scene.gravity.asArray();
  86320. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  86321. serializationObject.workerCollisions = scene.workerCollisions;
  86322. // Fog
  86323. if (scene.fogMode && scene.fogMode !== 0) {
  86324. serializationObject.fogMode = scene.fogMode;
  86325. serializationObject.fogColor = scene.fogColor.asArray();
  86326. serializationObject.fogStart = scene.fogStart;
  86327. serializationObject.fogEnd = scene.fogEnd;
  86328. serializationObject.fogDensity = scene.fogDensity;
  86329. }
  86330. //Physics
  86331. if (scene.isPhysicsEnabled()) {
  86332. var physicEngine = scene.getPhysicsEngine();
  86333. if (physicEngine) {
  86334. serializationObject.physicsEnabled = true;
  86335. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  86336. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  86337. }
  86338. }
  86339. // Metadata
  86340. if (scene.metadata) {
  86341. serializationObject.metadata = scene.metadata;
  86342. }
  86343. // Morph targets
  86344. serializationObject.morphTargetManagers = [];
  86345. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  86346. var abstractMesh = _a[_i];
  86347. var manager = abstractMesh.morphTargetManager;
  86348. if (manager) {
  86349. serializationObject.morphTargetManagers.push(manager.serialize());
  86350. }
  86351. }
  86352. // Lights
  86353. serializationObject.lights = [];
  86354. var index;
  86355. var light;
  86356. for (index = 0; index < scene.lights.length; index++) {
  86357. light = scene.lights[index];
  86358. if (!light.doNotSerialize) {
  86359. serializationObject.lights.push(light.serialize());
  86360. }
  86361. }
  86362. // Cameras
  86363. serializationObject.cameras = [];
  86364. for (index = 0; index < scene.cameras.length; index++) {
  86365. var camera = scene.cameras[index];
  86366. if (!camera.doNotSerialize) {
  86367. serializationObject.cameras.push(camera.serialize());
  86368. }
  86369. }
  86370. if (scene.activeCamera) {
  86371. serializationObject.activeCameraID = scene.activeCamera.id;
  86372. }
  86373. // Animations
  86374. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  86375. // Materials
  86376. serializationObject.materials = [];
  86377. serializationObject.multiMaterials = [];
  86378. var material;
  86379. for (index = 0; index < scene.materials.length; index++) {
  86380. material = scene.materials[index];
  86381. if (!material.doNotSerialize) {
  86382. serializationObject.materials.push(material.serialize());
  86383. }
  86384. }
  86385. // MultiMaterials
  86386. serializationObject.multiMaterials = [];
  86387. for (index = 0; index < scene.multiMaterials.length; index++) {
  86388. var multiMaterial = scene.multiMaterials[index];
  86389. serializationObject.multiMaterials.push(multiMaterial.serialize());
  86390. }
  86391. // Environment texture
  86392. if (scene.environmentTexture) {
  86393. serializationObject.environmentTexture = scene.environmentTexture.name;
  86394. }
  86395. // Skeletons
  86396. serializationObject.skeletons = [];
  86397. for (index = 0; index < scene.skeletons.length; index++) {
  86398. var skeleton = scene.skeletons[index];
  86399. if (!skeleton.doNotSerialize) {
  86400. serializationObject.skeletons.push(skeleton.serialize());
  86401. }
  86402. }
  86403. // Transform nodes
  86404. serializationObject.transformNodes = [];
  86405. for (index = 0; index < scene.transformNodes.length; index++) {
  86406. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  86407. }
  86408. // Geometries
  86409. serializationObject.geometries = {};
  86410. serializationObject.geometries.boxes = [];
  86411. serializationObject.geometries.spheres = [];
  86412. serializationObject.geometries.cylinders = [];
  86413. serializationObject.geometries.toruses = [];
  86414. serializationObject.geometries.grounds = [];
  86415. serializationObject.geometries.planes = [];
  86416. serializationObject.geometries.torusKnots = [];
  86417. serializationObject.geometries.vertexData = [];
  86418. serializedGeometries = [];
  86419. var geometries = scene.getGeometries();
  86420. for (index = 0; index < geometries.length; index++) {
  86421. var geometry = geometries[index];
  86422. if (geometry.isReady()) {
  86423. serializeGeometry(geometry, serializationObject.geometries);
  86424. }
  86425. }
  86426. // Meshes
  86427. serializationObject.meshes = [];
  86428. for (index = 0; index < scene.meshes.length; index++) {
  86429. var abstractMesh = scene.meshes[index];
  86430. if (abstractMesh instanceof BABYLON.Mesh) {
  86431. var mesh = abstractMesh;
  86432. if (!mesh.doNotSerialize) {
  86433. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  86434. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  86435. }
  86436. }
  86437. }
  86438. }
  86439. // Particles Systems
  86440. serializationObject.particleSystems = [];
  86441. for (index = 0; index < scene.particleSystems.length; index++) {
  86442. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  86443. }
  86444. // Lens flares
  86445. serializationObject.lensFlareSystems = [];
  86446. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  86447. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  86448. }
  86449. // Shadows
  86450. serializationObject.shadowGenerators = [];
  86451. for (index = 0; index < scene.lights.length; index++) {
  86452. light = scene.lights[index];
  86453. var shadowGenerator = light.getShadowGenerator();
  86454. if (shadowGenerator) {
  86455. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  86456. }
  86457. }
  86458. // Action Manager
  86459. if (scene.actionManager) {
  86460. serializationObject.actions = scene.actionManager.serialize("scene");
  86461. }
  86462. // Audio
  86463. serializationObject.sounds = [];
  86464. for (index = 0; index < scene.soundTracks.length; index++) {
  86465. var soundtrack = scene.soundTracks[index];
  86466. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  86467. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  86468. }
  86469. }
  86470. return serializationObject;
  86471. };
  86472. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  86473. if (withParents === void 0) { withParents = false; }
  86474. if (withChildren === void 0) { withChildren = false; }
  86475. var serializationObject = {};
  86476. SceneSerializer.ClearCache();
  86477. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  86478. if (withParents || withChildren) {
  86479. //deliberate for loop! not for each, appended should be processed as well.
  86480. for (var i = 0; i < toSerialize.length; ++i) {
  86481. if (withChildren) {
  86482. toSerialize[i].getDescendants().forEach(function (node) {
  86483. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  86484. toSerialize.push(node);
  86485. }
  86486. });
  86487. }
  86488. //make sure the array doesn't contain the object already
  86489. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  86490. toSerialize.push(toSerialize[i].parent);
  86491. }
  86492. }
  86493. }
  86494. toSerialize.forEach(function (mesh) {
  86495. finalizeSingleMesh(mesh, serializationObject);
  86496. });
  86497. return serializationObject;
  86498. };
  86499. return SceneSerializer;
  86500. }());
  86501. BABYLON.SceneSerializer = SceneSerializer;
  86502. })(BABYLON || (BABYLON = {}));
  86503. //# sourceMappingURL=babylon.sceneSerializer.js.map
  86504. var BABYLON;
  86505. (function (BABYLON) {
  86506. var ReflectionProbe = /** @class */ (function () {
  86507. function ReflectionProbe(name, size, scene, generateMipMaps) {
  86508. if (generateMipMaps === void 0) { generateMipMaps = true; }
  86509. var _this = this;
  86510. this.name = name;
  86511. this._viewMatrix = BABYLON.Matrix.Identity();
  86512. this._target = BABYLON.Vector3.Zero();
  86513. this._add = BABYLON.Vector3.Zero();
  86514. this._invertYAxis = false;
  86515. this.position = BABYLON.Vector3.Zero();
  86516. this._scene = scene;
  86517. this._scene.reflectionProbes.push(this);
  86518. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  86519. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  86520. switch (faceIndex) {
  86521. case 0:
  86522. _this._add.copyFromFloats(1, 0, 0);
  86523. break;
  86524. case 1:
  86525. _this._add.copyFromFloats(-1, 0, 0);
  86526. break;
  86527. case 2:
  86528. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  86529. break;
  86530. case 3:
  86531. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  86532. break;
  86533. case 4:
  86534. _this._add.copyFromFloats(0, 0, 1);
  86535. break;
  86536. case 5:
  86537. _this._add.copyFromFloats(0, 0, -1);
  86538. break;
  86539. }
  86540. if (_this._attachedMesh) {
  86541. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  86542. }
  86543. _this.position.addToRef(_this._add, _this._target);
  86544. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  86545. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  86546. scene._forcedViewPosition = _this.position;
  86547. });
  86548. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  86549. scene._forcedViewPosition = null;
  86550. scene.updateTransformMatrix(true);
  86551. });
  86552. if (scene.activeCamera) {
  86553. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  86554. }
  86555. }
  86556. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  86557. get: function () {
  86558. return this._renderTargetTexture.samples;
  86559. },
  86560. set: function (value) {
  86561. this._renderTargetTexture.samples = value;
  86562. },
  86563. enumerable: true,
  86564. configurable: true
  86565. });
  86566. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  86567. get: function () {
  86568. return this._renderTargetTexture.refreshRate;
  86569. },
  86570. set: function (value) {
  86571. this._renderTargetTexture.refreshRate = value;
  86572. },
  86573. enumerable: true,
  86574. configurable: true
  86575. });
  86576. ReflectionProbe.prototype.getScene = function () {
  86577. return this._scene;
  86578. };
  86579. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  86580. get: function () {
  86581. return this._renderTargetTexture;
  86582. },
  86583. enumerable: true,
  86584. configurable: true
  86585. });
  86586. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  86587. get: function () {
  86588. return this._renderTargetTexture.renderList;
  86589. },
  86590. enumerable: true,
  86591. configurable: true
  86592. });
  86593. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  86594. this._attachedMesh = mesh;
  86595. };
  86596. /**
  86597. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  86598. *
  86599. * @param renderingGroupId The rendering group id corresponding to its index
  86600. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  86601. */
  86602. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  86603. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  86604. };
  86605. ReflectionProbe.prototype.dispose = function () {
  86606. var index = this._scene.reflectionProbes.indexOf(this);
  86607. if (index !== -1) {
  86608. // Remove from the scene if found
  86609. this._scene.reflectionProbes.splice(index, 1);
  86610. }
  86611. if (this._renderTargetTexture) {
  86612. this._renderTargetTexture.dispose();
  86613. this._renderTargetTexture = null;
  86614. }
  86615. };
  86616. return ReflectionProbe;
  86617. }());
  86618. BABYLON.ReflectionProbe = ReflectionProbe;
  86619. })(BABYLON || (BABYLON = {}));
  86620. //# sourceMappingURL=babylon.reflectionProbe.js.map
  86621. var BABYLON;
  86622. (function (BABYLON) {
  86623. var Layer = /** @class */ (function () {
  86624. function Layer(name, imgUrl, scene, isBackground, color) {
  86625. this.name = name;
  86626. this.scale = new BABYLON.Vector2(1, 1);
  86627. this.offset = new BABYLON.Vector2(0, 0);
  86628. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  86629. this.layerMask = 0x0FFFFFFF;
  86630. this._vertexBuffers = {};
  86631. // Events
  86632. /**
  86633. * An event triggered when the layer is disposed.
  86634. * @type {BABYLON.Observable}
  86635. */
  86636. this.onDisposeObservable = new BABYLON.Observable();
  86637. /**
  86638. * An event triggered before rendering the scene
  86639. * @type {BABYLON.Observable}
  86640. */
  86641. this.onBeforeRenderObservable = new BABYLON.Observable();
  86642. /**
  86643. * An event triggered after rendering the scene
  86644. * @type {BABYLON.Observable}
  86645. */
  86646. this.onAfterRenderObservable = new BABYLON.Observable();
  86647. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  86648. this.isBackground = isBackground === undefined ? true : isBackground;
  86649. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  86650. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  86651. this._scene.layers.push(this);
  86652. var engine = this._scene.getEngine();
  86653. // VBO
  86654. var vertices = [];
  86655. vertices.push(1, 1);
  86656. vertices.push(-1, 1);
  86657. vertices.push(-1, -1);
  86658. vertices.push(1, -1);
  86659. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  86660. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  86661. this._createIndexBuffer();
  86662. // Effects
  86663. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  86664. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  86665. }
  86666. Object.defineProperty(Layer.prototype, "onDispose", {
  86667. set: function (callback) {
  86668. if (this._onDisposeObserver) {
  86669. this.onDisposeObservable.remove(this._onDisposeObserver);
  86670. }
  86671. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  86672. },
  86673. enumerable: true,
  86674. configurable: true
  86675. });
  86676. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  86677. set: function (callback) {
  86678. if (this._onBeforeRenderObserver) {
  86679. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  86680. }
  86681. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  86682. },
  86683. enumerable: true,
  86684. configurable: true
  86685. });
  86686. Object.defineProperty(Layer.prototype, "onAfterRender", {
  86687. set: function (callback) {
  86688. if (this._onAfterRenderObserver) {
  86689. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  86690. }
  86691. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  86692. },
  86693. enumerable: true,
  86694. configurable: true
  86695. });
  86696. Layer.prototype._createIndexBuffer = function () {
  86697. var engine = this._scene.getEngine();
  86698. // Indices
  86699. var indices = [];
  86700. indices.push(0);
  86701. indices.push(1);
  86702. indices.push(2);
  86703. indices.push(0);
  86704. indices.push(2);
  86705. indices.push(3);
  86706. this._indexBuffer = engine.createIndexBuffer(indices);
  86707. };
  86708. Layer.prototype._rebuild = function () {
  86709. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86710. if (vb) {
  86711. vb._rebuild();
  86712. }
  86713. this._createIndexBuffer();
  86714. };
  86715. Layer.prototype.render = function () {
  86716. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  86717. // Check
  86718. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  86719. return;
  86720. var engine = this._scene.getEngine();
  86721. this.onBeforeRenderObservable.notifyObservers(this);
  86722. // Render
  86723. engine.enableEffect(currentEffect);
  86724. engine.setState(false);
  86725. // Texture
  86726. currentEffect.setTexture("textureSampler", this.texture);
  86727. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  86728. // Color
  86729. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  86730. // Scale / offset
  86731. currentEffect.setVector2("offset", this.offset);
  86732. currentEffect.setVector2("scale", this.scale);
  86733. // VBOs
  86734. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  86735. // Draw order
  86736. if (!this.alphaTest) {
  86737. engine.setAlphaMode(this.alphaBlendingMode);
  86738. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86739. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  86740. }
  86741. else {
  86742. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86743. }
  86744. this.onAfterRenderObservable.notifyObservers(this);
  86745. };
  86746. Layer.prototype.dispose = function () {
  86747. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86748. if (vertexBuffer) {
  86749. vertexBuffer.dispose();
  86750. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86751. }
  86752. if (this._indexBuffer) {
  86753. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86754. this._indexBuffer = null;
  86755. }
  86756. if (this.texture) {
  86757. this.texture.dispose();
  86758. this.texture = null;
  86759. }
  86760. // Remove from scene
  86761. var index = this._scene.layers.indexOf(this);
  86762. this._scene.layers.splice(index, 1);
  86763. // Callback
  86764. this.onDisposeObservable.notifyObservers(this);
  86765. this.onDisposeObservable.clear();
  86766. this.onAfterRenderObservable.clear();
  86767. this.onBeforeRenderObservable.clear();
  86768. };
  86769. return Layer;
  86770. }());
  86771. BABYLON.Layer = Layer;
  86772. })(BABYLON || (BABYLON = {}));
  86773. //# sourceMappingURL=babylon.layer.js.map
  86774. var BABYLON;
  86775. (function (BABYLON) {
  86776. var TextureTools = /** @class */ (function () {
  86777. function TextureTools() {
  86778. }
  86779. /**
  86780. * Uses the GPU to create a copy texture rescaled at a given size
  86781. * @param texture Texture to copy from
  86782. * @param width Desired width
  86783. * @param height Desired height
  86784. * @return Generated texture
  86785. */
  86786. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  86787. if (useBilinearMode === void 0) { useBilinearMode = true; }
  86788. var scene = texture.getScene();
  86789. var engine = scene.getEngine();
  86790. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  86791. rtt.wrapU = texture.wrapU;
  86792. rtt.wrapV = texture.wrapV;
  86793. rtt.uOffset = texture.uOffset;
  86794. rtt.vOffset = texture.vOffset;
  86795. rtt.uScale = texture.uScale;
  86796. rtt.vScale = texture.vScale;
  86797. rtt.uAng = texture.uAng;
  86798. rtt.vAng = texture.vAng;
  86799. rtt.wAng = texture.wAng;
  86800. rtt.coordinatesIndex = texture.coordinatesIndex;
  86801. rtt.level = texture.level;
  86802. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  86803. rtt._texture.isReady = false;
  86804. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86805. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86806. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  86807. passPostProcess.getEffect().executeWhenCompiled(function () {
  86808. passPostProcess.onApply = function (effect) {
  86809. effect.setTexture("textureSampler", texture);
  86810. };
  86811. var internalTexture = rtt.getInternalTexture();
  86812. if (internalTexture) {
  86813. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  86814. engine.unBindFramebuffer(internalTexture);
  86815. rtt.disposeFramebufferObjects();
  86816. passPostProcess.dispose();
  86817. internalTexture.isReady = true;
  86818. }
  86819. });
  86820. return rtt;
  86821. };
  86822. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  86823. if (!scene._environmentBRDFTexture) {
  86824. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86825. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86826. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86827. scene._environmentBRDFTexture = texture;
  86828. }
  86829. return scene._environmentBRDFTexture;
  86830. };
  86831. 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=";
  86832. return TextureTools;
  86833. }());
  86834. BABYLON.TextureTools = TextureTools;
  86835. })(BABYLON || (BABYLON = {}));
  86836. //# sourceMappingURL=babylon.textureTools.js.map
  86837. var BABYLON;
  86838. (function (BABYLON) {
  86839. var FramingBehavior = /** @class */ (function () {
  86840. function FramingBehavior() {
  86841. this._mode = FramingBehavior.FitFrustumSidesMode;
  86842. this._radiusScale = 1.0;
  86843. this._positionScale = 0.5;
  86844. this._defaultElevation = 0.3;
  86845. this._elevationReturnTime = 1500;
  86846. this._elevationReturnWaitTime = 1000;
  86847. this._zoomStopsAnimation = false;
  86848. this._framingTime = 1500;
  86849. this._isPointerDown = false;
  86850. this._lastInteractionTime = -Infinity;
  86851. // Framing control
  86852. this._animatables = new Array();
  86853. this._betaIsAnimating = false;
  86854. }
  86855. Object.defineProperty(FramingBehavior.prototype, "name", {
  86856. get: function () {
  86857. return "Framing";
  86858. },
  86859. enumerable: true,
  86860. configurable: true
  86861. });
  86862. Object.defineProperty(FramingBehavior.prototype, "mode", {
  86863. /**
  86864. * Gets current mode used by the behavior.
  86865. */
  86866. get: function () {
  86867. return this._mode;
  86868. },
  86869. /**
  86870. * Sets the current mode used by the behavior
  86871. */
  86872. set: function (mode) {
  86873. this._mode = mode;
  86874. },
  86875. enumerable: true,
  86876. configurable: true
  86877. });
  86878. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  86879. /**
  86880. * Gets the scale applied to the radius
  86881. */
  86882. get: function () {
  86883. return this._radiusScale;
  86884. },
  86885. /**
  86886. * Sets the scale applied to the radius (1 by default)
  86887. */
  86888. set: function (radius) {
  86889. this._radiusScale = radius;
  86890. },
  86891. enumerable: true,
  86892. configurable: true
  86893. });
  86894. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  86895. /**
  86896. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  86897. */
  86898. get: function () {
  86899. return this._positionScale;
  86900. },
  86901. /**
  86902. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  86903. */
  86904. set: function (scale) {
  86905. this._positionScale = scale;
  86906. },
  86907. enumerable: true,
  86908. configurable: true
  86909. });
  86910. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  86911. /**
  86912. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  86913. * behaviour is triggered, in radians.
  86914. */
  86915. get: function () {
  86916. return this._defaultElevation;
  86917. },
  86918. /**
  86919. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  86920. * behaviour is triggered, in radians.
  86921. */
  86922. set: function (elevation) {
  86923. this._defaultElevation = elevation;
  86924. },
  86925. enumerable: true,
  86926. configurable: true
  86927. });
  86928. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  86929. /**
  86930. * Gets the time (in milliseconds) taken to return to the default beta position.
  86931. * Negative value indicates camera should not return to default.
  86932. */
  86933. get: function () {
  86934. return this._elevationReturnTime;
  86935. },
  86936. /**
  86937. * Sets the time (in milliseconds) taken to return to the default beta position.
  86938. * Negative value indicates camera should not return to default.
  86939. */
  86940. set: function (speed) {
  86941. this._elevationReturnTime = speed;
  86942. },
  86943. enumerable: true,
  86944. configurable: true
  86945. });
  86946. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  86947. /**
  86948. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  86949. */
  86950. get: function () {
  86951. return this._elevationReturnWaitTime;
  86952. },
  86953. /**
  86954. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  86955. */
  86956. set: function (time) {
  86957. this._elevationReturnWaitTime = time;
  86958. },
  86959. enumerable: true,
  86960. configurable: true
  86961. });
  86962. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  86963. /**
  86964. * Gets the flag that indicates if user zooming should stop animation.
  86965. */
  86966. get: function () {
  86967. return this._zoomStopsAnimation;
  86968. },
  86969. /**
  86970. * Sets the flag that indicates if user zooming should stop animation.
  86971. */
  86972. set: function (flag) {
  86973. this._zoomStopsAnimation = flag;
  86974. },
  86975. enumerable: true,
  86976. configurable: true
  86977. });
  86978. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  86979. /**
  86980. * Gets the transition time when framing the mesh, in milliseconds
  86981. */
  86982. get: function () {
  86983. return this._framingTime;
  86984. },
  86985. /**
  86986. * Sets the transition time when framing the mesh, in milliseconds
  86987. */
  86988. set: function (time) {
  86989. this._framingTime = time;
  86990. },
  86991. enumerable: true,
  86992. configurable: true
  86993. });
  86994. FramingBehavior.prototype.init = function () {
  86995. // Do notihng
  86996. };
  86997. FramingBehavior.prototype.attach = function (camera) {
  86998. var _this = this;
  86999. this._attachedCamera = camera;
  87000. var scene = this._attachedCamera.getScene();
  87001. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  87002. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  87003. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  87004. _this._isPointerDown = true;
  87005. return;
  87006. }
  87007. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  87008. _this._isPointerDown = false;
  87009. }
  87010. });
  87011. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  87012. if (mesh) {
  87013. _this.zoomOnMesh(mesh);
  87014. }
  87015. });
  87016. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  87017. // Stop the animation if there is user interaction and the animation should stop for this interaction
  87018. _this._applyUserInteraction();
  87019. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  87020. // back to the default position after a given timeout
  87021. _this._maintainCameraAboveGround();
  87022. });
  87023. };
  87024. FramingBehavior.prototype.detach = function () {
  87025. if (!this._attachedCamera) {
  87026. return;
  87027. }
  87028. var scene = this._attachedCamera.getScene();
  87029. if (this._onPrePointerObservableObserver) {
  87030. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  87031. }
  87032. if (this._onAfterCheckInputsObserver) {
  87033. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  87034. }
  87035. if (this._onMeshTargetChangedObserver) {
  87036. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  87037. }
  87038. this._attachedCamera = null;
  87039. };
  87040. /**
  87041. * Targets the given mesh and updates zoom level accordingly.
  87042. * @param mesh The mesh to target.
  87043. * @param radius Optional. If a cached radius position already exists, overrides default.
  87044. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87045. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87046. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87047. */
  87048. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  87049. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87050. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87051. mesh.computeWorldMatrix(true);
  87052. var boundingBox = mesh.getBoundingInfo().boundingBox;
  87053. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  87054. };
  87055. /**
  87056. * Targets the given mesh with its children and updates zoom level accordingly.
  87057. * @param mesh The mesh to target.
  87058. * @param radius Optional. If a cached radius position already exists, overrides default.
  87059. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87060. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87061. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87062. */
  87063. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  87064. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87065. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87066. mesh.computeWorldMatrix(true);
  87067. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  87068. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  87069. };
  87070. /**
  87071. * Targets the given meshes with their children and updates zoom level accordingly.
  87072. * @param meshes The mesh to target.
  87073. * @param radius Optional. If a cached radius position already exists, overrides default.
  87074. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87075. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87076. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87077. */
  87078. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  87079. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87080. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87081. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  87082. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  87083. for (var i = 0; i < meshes.length; i++) {
  87084. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  87085. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  87086. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  87087. }
  87088. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  87089. };
  87090. /**
  87091. * Targets the given mesh and updates zoom level accordingly.
  87092. * @param mesh The mesh to target.
  87093. * @param radius Optional. If a cached radius position already exists, overrides default.
  87094. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87095. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87096. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87097. */
  87098. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  87099. var _this = this;
  87100. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87101. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87102. var zoomTarget;
  87103. if (!this._attachedCamera) {
  87104. return;
  87105. }
  87106. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  87107. var bottom = minimumWorld.y;
  87108. var top = maximumWorld.y;
  87109. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  87110. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  87111. if (focusOnOriginXZ) {
  87112. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  87113. }
  87114. else {
  87115. var centerWorld = minimumWorld.add(radiusWorld);
  87116. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  87117. }
  87118. if (!this._vectorTransition) {
  87119. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  87120. }
  87121. this._betaIsAnimating = true;
  87122. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  87123. if (animatable) {
  87124. this._animatables.push(animatable);
  87125. }
  87126. // sets the radius and lower radius bounds
  87127. // Small delta ensures camera is not always at lower zoom limit.
  87128. var radius = 0;
  87129. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  87130. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  87131. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  87132. radius = position;
  87133. }
  87134. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  87135. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  87136. if (this._attachedCamera.lowerRadiusLimit === null) {
  87137. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  87138. }
  87139. }
  87140. // Set sensibilities
  87141. var extend = maximumWorld.subtract(minimumWorld).length();
  87142. this._attachedCamera.panningSensibility = 5000 / extend;
  87143. this._attachedCamera.wheelPrecision = 100 / radius;
  87144. // transition to new radius
  87145. if (!this._radiusTransition) {
  87146. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  87147. }
  87148. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  87149. if (onAnimationEnd) {
  87150. onAnimationEnd();
  87151. }
  87152. if (_this._attachedCamera) {
  87153. _this._attachedCamera.storeState();
  87154. }
  87155. });
  87156. if (animatable) {
  87157. this._animatables.push(animatable);
  87158. }
  87159. };
  87160. /**
  87161. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  87162. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  87163. * frustum width.
  87164. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  87165. * to fully enclose the mesh in the viewing frustum.
  87166. */
  87167. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  87168. var size = maximumWorld.subtract(minimumWorld);
  87169. var boxVectorGlobalDiagonal = size.length();
  87170. var frustumSlope = this._getFrustumSlope();
  87171. // Formula for setting distance
  87172. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  87173. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  87174. // Horizon distance
  87175. var radius = radiusWithoutFraming * this._radiusScale;
  87176. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  87177. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  87178. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  87179. var camera = this._attachedCamera;
  87180. if (!camera) {
  87181. return 0;
  87182. }
  87183. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  87184. // Don't exceed the requested limit
  87185. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  87186. }
  87187. // Don't exceed the upper radius limit
  87188. if (camera.upperRadiusLimit) {
  87189. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  87190. }
  87191. return distance;
  87192. };
  87193. /**
  87194. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  87195. * is automatically returned to its default position (expected to be above ground plane).
  87196. */
  87197. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  87198. var _this = this;
  87199. if (this._elevationReturnTime < 0) {
  87200. return;
  87201. }
  87202. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  87203. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  87204. var limitBeta = Math.PI * 0.5;
  87205. // Bring the camera back up if below the ground plane
  87206. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  87207. this._betaIsAnimating = true;
  87208. //Transition to new position
  87209. this.stopAllAnimations();
  87210. if (!this._betaTransition) {
  87211. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  87212. }
  87213. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  87214. _this._clearAnimationLocks();
  87215. _this.stopAllAnimations();
  87216. });
  87217. if (animatabe) {
  87218. this._animatables.push(animatabe);
  87219. }
  87220. }
  87221. };
  87222. /**
  87223. * Returns the frustum slope based on the canvas ratio and camera FOV
  87224. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  87225. */
  87226. FramingBehavior.prototype._getFrustumSlope = function () {
  87227. // Calculate the viewport ratio
  87228. // Aspect Ratio is Height/Width.
  87229. var camera = this._attachedCamera;
  87230. if (!camera) {
  87231. return BABYLON.Vector2.Zero();
  87232. }
  87233. var engine = camera.getScene().getEngine();
  87234. var aspectRatio = engine.getAspectRatio(camera);
  87235. // Camera FOV is the vertical field of view (top-bottom) in radians.
  87236. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  87237. var frustumSlopeY = Math.tan(camera.fov / 2);
  87238. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  87239. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  87240. // along the forward vector.
  87241. var frustumSlopeX = frustumSlopeY * aspectRatio;
  87242. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  87243. };
  87244. /**
  87245. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  87246. */
  87247. FramingBehavior.prototype._clearAnimationLocks = function () {
  87248. this._betaIsAnimating = false;
  87249. };
  87250. /**
  87251. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  87252. */
  87253. FramingBehavior.prototype._applyUserInteraction = function () {
  87254. if (this.isUserIsMoving) {
  87255. this._lastInteractionTime = BABYLON.Tools.Now;
  87256. this.stopAllAnimations();
  87257. this._clearAnimationLocks();
  87258. }
  87259. };
  87260. /**
  87261. * Stops and removes all animations that have been applied to the camera
  87262. */
  87263. FramingBehavior.prototype.stopAllAnimations = function () {
  87264. if (this._attachedCamera) {
  87265. this._attachedCamera.animations = [];
  87266. }
  87267. while (this._animatables.length) {
  87268. if (this._animatables[0]) {
  87269. this._animatables[0].onAnimationEnd = null;
  87270. this._animatables[0].stop();
  87271. }
  87272. this._animatables.shift();
  87273. }
  87274. };
  87275. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  87276. /**
  87277. * Gets a value indicating if the user is moving the camera
  87278. */
  87279. get: function () {
  87280. if (!this._attachedCamera) {
  87281. return false;
  87282. }
  87283. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  87284. this._attachedCamera.inertialBetaOffset !== 0 ||
  87285. this._attachedCamera.inertialRadiusOffset !== 0 ||
  87286. this._attachedCamera.inertialPanningX !== 0 ||
  87287. this._attachedCamera.inertialPanningY !== 0 ||
  87288. this._isPointerDown;
  87289. },
  87290. enumerable: true,
  87291. configurable: true
  87292. });
  87293. /**
  87294. * The easing function used by animations
  87295. */
  87296. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  87297. /**
  87298. * The easing mode used by animations
  87299. */
  87300. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  87301. // Statics
  87302. /**
  87303. * The camera can move all the way towards the mesh.
  87304. */
  87305. FramingBehavior.IgnoreBoundsSizeMode = 0;
  87306. /**
  87307. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  87308. */
  87309. FramingBehavior.FitFrustumSidesMode = 1;
  87310. return FramingBehavior;
  87311. }());
  87312. BABYLON.FramingBehavior = FramingBehavior;
  87313. })(BABYLON || (BABYLON = {}));
  87314. //# sourceMappingURL=babylon.framingBehavior.js.map
  87315. var BABYLON;
  87316. (function (BABYLON) {
  87317. /**
  87318. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  87319. */
  87320. var BouncingBehavior = /** @class */ (function () {
  87321. function BouncingBehavior() {
  87322. /**
  87323. * The duration of the animation, in milliseconds
  87324. */
  87325. this.transitionDuration = 450;
  87326. /**
  87327. * Length of the distance animated by the transition when lower radius is reached
  87328. */
  87329. this.lowerRadiusTransitionRange = 2;
  87330. /**
  87331. * Length of the distance animated by the transition when upper radius is reached
  87332. */
  87333. this.upperRadiusTransitionRange = -2;
  87334. this._autoTransitionRange = false;
  87335. // Animations
  87336. this._radiusIsAnimating = false;
  87337. this._radiusBounceTransition = null;
  87338. this._animatables = new Array();
  87339. }
  87340. Object.defineProperty(BouncingBehavior.prototype, "name", {
  87341. get: function () {
  87342. return "Bouncing";
  87343. },
  87344. enumerable: true,
  87345. configurable: true
  87346. });
  87347. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  87348. /**
  87349. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  87350. */
  87351. get: function () {
  87352. return this._autoTransitionRange;
  87353. },
  87354. /**
  87355. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  87356. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  87357. */
  87358. set: function (value) {
  87359. var _this = this;
  87360. if (this._autoTransitionRange === value) {
  87361. return;
  87362. }
  87363. this._autoTransitionRange = value;
  87364. var camera = this._attachedCamera;
  87365. if (!camera) {
  87366. return;
  87367. }
  87368. if (value) {
  87369. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  87370. if (!mesh) {
  87371. return;
  87372. }
  87373. mesh.computeWorldMatrix(true);
  87374. var diagonal = mesh.getBoundingInfo().diagonalLength;
  87375. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  87376. _this.upperRadiusTransitionRange = diagonal * 0.05;
  87377. });
  87378. }
  87379. else if (this._onMeshTargetChangedObserver) {
  87380. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  87381. }
  87382. },
  87383. enumerable: true,
  87384. configurable: true
  87385. });
  87386. BouncingBehavior.prototype.init = function () {
  87387. // Do notihng
  87388. };
  87389. BouncingBehavior.prototype.attach = function (camera) {
  87390. var _this = this;
  87391. this._attachedCamera = camera;
  87392. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  87393. if (!_this._attachedCamera) {
  87394. return;
  87395. }
  87396. // Add the bounce animation to the lower radius limit
  87397. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  87398. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  87399. }
  87400. // Add the bounce animation to the upper radius limit
  87401. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  87402. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  87403. }
  87404. });
  87405. };
  87406. BouncingBehavior.prototype.detach = function () {
  87407. if (!this._attachedCamera) {
  87408. return;
  87409. }
  87410. if (this._onAfterCheckInputsObserver) {
  87411. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  87412. }
  87413. if (this._onMeshTargetChangedObserver) {
  87414. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  87415. }
  87416. this._attachedCamera = null;
  87417. };
  87418. /**
  87419. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  87420. * @param radiusLimit The limit to check against.
  87421. * @return Bool to indicate if at limit.
  87422. */
  87423. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  87424. if (!this._attachedCamera) {
  87425. return false;
  87426. }
  87427. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  87428. return true;
  87429. }
  87430. return false;
  87431. };
  87432. /**
  87433. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  87434. * @param radiusDelta The delta by which to animate to. Can be negative.
  87435. */
  87436. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  87437. var _this = this;
  87438. if (!this._attachedCamera) {
  87439. return;
  87440. }
  87441. if (!this._radiusBounceTransition) {
  87442. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  87443. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  87444. }
  87445. // Prevent zoom until bounce has completed
  87446. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  87447. this._attachedCamera.wheelPrecision = Infinity;
  87448. this._attachedCamera.inertialRadiusOffset = 0;
  87449. // Animate to the radius limit
  87450. this.stopAllAnimations();
  87451. this._radiusIsAnimating = true;
  87452. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  87453. if (animatable) {
  87454. this._animatables.push(animatable);
  87455. }
  87456. };
  87457. /**
  87458. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  87459. */
  87460. BouncingBehavior.prototype._clearAnimationLocks = function () {
  87461. this._radiusIsAnimating = false;
  87462. if (this._attachedCamera) {
  87463. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  87464. }
  87465. };
  87466. /**
  87467. * Stops and removes all animations that have been applied to the camera
  87468. */
  87469. BouncingBehavior.prototype.stopAllAnimations = function () {
  87470. if (this._attachedCamera) {
  87471. this._attachedCamera.animations = [];
  87472. }
  87473. while (this._animatables.length) {
  87474. this._animatables[0].onAnimationEnd = null;
  87475. this._animatables[0].stop();
  87476. this._animatables.shift();
  87477. }
  87478. };
  87479. /**
  87480. * The easing function used by animations
  87481. */
  87482. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  87483. /**
  87484. * The easing mode used by animations
  87485. */
  87486. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  87487. return BouncingBehavior;
  87488. }());
  87489. BABYLON.BouncingBehavior = BouncingBehavior;
  87490. })(BABYLON || (BABYLON = {}));
  87491. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  87492. var BABYLON;
  87493. (function (BABYLON) {
  87494. var AutoRotationBehavior = /** @class */ (function () {
  87495. function AutoRotationBehavior() {
  87496. this._zoomStopsAnimation = false;
  87497. this._idleRotationSpeed = 0.05;
  87498. this._idleRotationWaitTime = 2000;
  87499. this._idleRotationSpinupTime = 2000;
  87500. this._isPointerDown = false;
  87501. this._lastFrameTime = null;
  87502. this._lastInteractionTime = -Infinity;
  87503. this._cameraRotationSpeed = 0;
  87504. this._lastFrameRadius = 0;
  87505. }
  87506. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  87507. get: function () {
  87508. return "AutoRotation";
  87509. },
  87510. enumerable: true,
  87511. configurable: true
  87512. });
  87513. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  87514. /**
  87515. * Gets the flag that indicates if user zooming should stop animation.
  87516. */
  87517. get: function () {
  87518. return this._zoomStopsAnimation;
  87519. },
  87520. /**
  87521. * Sets the flag that indicates if user zooming should stop animation.
  87522. */
  87523. set: function (flag) {
  87524. this._zoomStopsAnimation = flag;
  87525. },
  87526. enumerable: true,
  87527. configurable: true
  87528. });
  87529. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  87530. /**
  87531. * Gets the default speed at which the camera rotates around the model.
  87532. */
  87533. get: function () {
  87534. return this._idleRotationSpeed;
  87535. },
  87536. /**
  87537. * Sets the default speed at which the camera rotates around the model.
  87538. */
  87539. set: function (speed) {
  87540. this._idleRotationSpeed = speed;
  87541. },
  87542. enumerable: true,
  87543. configurable: true
  87544. });
  87545. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  87546. /**
  87547. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  87548. */
  87549. get: function () {
  87550. return this._idleRotationWaitTime;
  87551. },
  87552. /**
  87553. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  87554. */
  87555. set: function (time) {
  87556. this._idleRotationWaitTime = time;
  87557. },
  87558. enumerable: true,
  87559. configurable: true
  87560. });
  87561. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  87562. /**
  87563. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  87564. */
  87565. get: function () {
  87566. return this._idleRotationSpinupTime;
  87567. },
  87568. /**
  87569. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  87570. */
  87571. set: function (time) {
  87572. this._idleRotationSpinupTime = time;
  87573. },
  87574. enumerable: true,
  87575. configurable: true
  87576. });
  87577. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  87578. /**
  87579. * Gets a value indicating if the camera is currently rotating because of this behavior
  87580. */
  87581. get: function () {
  87582. return Math.abs(this._cameraRotationSpeed) > 0;
  87583. },
  87584. enumerable: true,
  87585. configurable: true
  87586. });
  87587. AutoRotationBehavior.prototype.init = function () {
  87588. // Do notihng
  87589. };
  87590. AutoRotationBehavior.prototype.attach = function (camera) {
  87591. var _this = this;
  87592. this._attachedCamera = camera;
  87593. var scene = this._attachedCamera.getScene();
  87594. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  87595. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  87596. _this._isPointerDown = true;
  87597. return;
  87598. }
  87599. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  87600. _this._isPointerDown = false;
  87601. }
  87602. });
  87603. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  87604. var now = BABYLON.Tools.Now;
  87605. var dt = 0;
  87606. if (_this._lastFrameTime != null) {
  87607. dt = now - _this._lastFrameTime;
  87608. }
  87609. _this._lastFrameTime = now;
  87610. // Stop the animation if there is user interaction and the animation should stop for this interaction
  87611. _this._applyUserInteraction();
  87612. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  87613. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  87614. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  87615. // Step camera rotation by rotation speed
  87616. if (_this._attachedCamera) {
  87617. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  87618. }
  87619. });
  87620. };
  87621. AutoRotationBehavior.prototype.detach = function () {
  87622. if (!this._attachedCamera) {
  87623. return;
  87624. }
  87625. var scene = this._attachedCamera.getScene();
  87626. if (this._onPrePointerObservableObserver) {
  87627. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  87628. }
  87629. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  87630. this._attachedCamera = null;
  87631. };
  87632. /**
  87633. * Returns true if user is scrolling.
  87634. * @return true if user is scrolling.
  87635. */
  87636. AutoRotationBehavior.prototype._userIsZooming = function () {
  87637. if (!this._attachedCamera) {
  87638. return false;
  87639. }
  87640. return this._attachedCamera.inertialRadiusOffset !== 0;
  87641. };
  87642. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  87643. if (!this._attachedCamera) {
  87644. return false;
  87645. }
  87646. var zoomHasHitLimit = false;
  87647. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  87648. zoomHasHitLimit = true;
  87649. }
  87650. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  87651. this._lastFrameRadius = this._attachedCamera.radius;
  87652. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  87653. };
  87654. /**
  87655. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  87656. */
  87657. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  87658. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  87659. this._lastInteractionTime = BABYLON.Tools.Now;
  87660. }
  87661. };
  87662. // Tools
  87663. AutoRotationBehavior.prototype._userIsMoving = function () {
  87664. if (!this._attachedCamera) {
  87665. return false;
  87666. }
  87667. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  87668. this._attachedCamera.inertialBetaOffset !== 0 ||
  87669. this._attachedCamera.inertialRadiusOffset !== 0 ||
  87670. this._attachedCamera.inertialPanningX !== 0 ||
  87671. this._attachedCamera.inertialPanningY !== 0 ||
  87672. this._isPointerDown;
  87673. };
  87674. return AutoRotationBehavior;
  87675. }());
  87676. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  87677. })(BABYLON || (BABYLON = {}));
  87678. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  87679. var BABYLON;
  87680. (function (BABYLON) {
  87681. var NullEngineOptions = /** @class */ (function () {
  87682. function NullEngineOptions() {
  87683. this.renderWidth = 512;
  87684. this.renderHeight = 256;
  87685. this.textureSize = 512;
  87686. this.deterministicLockstep = false;
  87687. this.lockstepMaxSteps = 4;
  87688. }
  87689. return NullEngineOptions;
  87690. }());
  87691. BABYLON.NullEngineOptions = NullEngineOptions;
  87692. /**
  87693. * The null engine class provides support for headless version of babylon.js.
  87694. * This can be used in server side scenario or for testing purposes
  87695. */
  87696. var NullEngine = /** @class */ (function (_super) {
  87697. __extends(NullEngine, _super);
  87698. function NullEngine(options) {
  87699. if (options === void 0) { options = new NullEngineOptions(); }
  87700. var _this = _super.call(this, null) || this;
  87701. if (options.deterministicLockstep === undefined) {
  87702. options.deterministicLockstep = false;
  87703. }
  87704. if (options.lockstepMaxSteps === undefined) {
  87705. options.lockstepMaxSteps = 4;
  87706. }
  87707. _this._options = options;
  87708. // Init caps
  87709. // We consider we are on a webgl1 capable device
  87710. _this._caps = new BABYLON.EngineCapabilities();
  87711. _this._caps.maxTexturesImageUnits = 16;
  87712. _this._caps.maxVertexTextureImageUnits = 16;
  87713. _this._caps.maxTextureSize = 512;
  87714. _this._caps.maxCubemapTextureSize = 512;
  87715. _this._caps.maxRenderTextureSize = 512;
  87716. _this._caps.maxVertexAttribs = 16;
  87717. _this._caps.maxVaryingVectors = 16;
  87718. _this._caps.maxFragmentUniformVectors = 16;
  87719. _this._caps.maxVertexUniformVectors = 16;
  87720. // Extensions
  87721. _this._caps.standardDerivatives = false;
  87722. _this._caps.astc = null;
  87723. _this._caps.s3tc = null;
  87724. _this._caps.pvrtc = null;
  87725. _this._caps.etc1 = null;
  87726. _this._caps.etc2 = null;
  87727. _this._caps.textureAnisotropicFilterExtension = null;
  87728. _this._caps.maxAnisotropy = 0;
  87729. _this._caps.uintIndices = false;
  87730. _this._caps.fragmentDepthSupported = false;
  87731. _this._caps.highPrecisionShaderSupported = true;
  87732. _this._caps.colorBufferFloat = false;
  87733. _this._caps.textureFloat = false;
  87734. _this._caps.textureFloatLinearFiltering = false;
  87735. _this._caps.textureFloatRender = false;
  87736. _this._caps.textureHalfFloat = false;
  87737. _this._caps.textureHalfFloatLinearFiltering = false;
  87738. _this._caps.textureHalfFloatRender = false;
  87739. _this._caps.textureLOD = false;
  87740. _this._caps.drawBuffersExtension = false;
  87741. _this._caps.depthTextureExtension = false;
  87742. _this._caps.vertexArrayObject = false;
  87743. _this._caps.instancedArrays = false;
  87744. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  87745. // Wrappers
  87746. if (typeof URL === "undefined") {
  87747. URL = {
  87748. createObjectURL: function () { },
  87749. revokeObjectURL: function () { }
  87750. };
  87751. }
  87752. if (typeof Blob === "undefined") {
  87753. Blob = function () { };
  87754. }
  87755. return _this;
  87756. }
  87757. NullEngine.prototype.isDeterministicLockStep = function () {
  87758. return this._options.deterministicLockstep;
  87759. };
  87760. NullEngine.prototype.getLockstepMaxSteps = function () {
  87761. return this._options.lockstepMaxSteps;
  87762. };
  87763. NullEngine.prototype.getHardwareScalingLevel = function () {
  87764. return 1.0;
  87765. };
  87766. NullEngine.prototype.createVertexBuffer = function (vertices) {
  87767. return {
  87768. capacity: 0,
  87769. references: 1,
  87770. is32Bits: false
  87771. };
  87772. };
  87773. NullEngine.prototype.createIndexBuffer = function (indices) {
  87774. return {
  87775. capacity: 0,
  87776. references: 1,
  87777. is32Bits: false
  87778. };
  87779. };
  87780. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  87781. if (stencil === void 0) { stencil = false; }
  87782. };
  87783. NullEngine.prototype.getRenderWidth = function (useScreen) {
  87784. if (useScreen === void 0) { useScreen = false; }
  87785. if (!useScreen && this._currentRenderTarget) {
  87786. return this._currentRenderTarget.width;
  87787. }
  87788. return this._options.renderWidth;
  87789. };
  87790. NullEngine.prototype.getRenderHeight = function (useScreen) {
  87791. if (useScreen === void 0) { useScreen = false; }
  87792. if (!useScreen && this._currentRenderTarget) {
  87793. return this._currentRenderTarget.height;
  87794. }
  87795. return this._options.renderHeight;
  87796. };
  87797. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  87798. this._cachedViewport = viewport;
  87799. };
  87800. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  87801. return {
  87802. transformFeedback: null,
  87803. __SPECTOR_rebuildProgram: null
  87804. };
  87805. };
  87806. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  87807. return [];
  87808. };
  87809. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  87810. return [];
  87811. };
  87812. NullEngine.prototype.bindSamplers = function (effect) {
  87813. this._currentEffect = null;
  87814. };
  87815. NullEngine.prototype.enableEffect = function (effect) {
  87816. this._currentEffect = effect;
  87817. if (effect.onBind) {
  87818. effect.onBind(effect);
  87819. }
  87820. effect.onBindObservable.notifyObservers(effect);
  87821. };
  87822. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  87823. if (zOffset === void 0) { zOffset = 0; }
  87824. if (reverseSide === void 0) { reverseSide = false; }
  87825. };
  87826. NullEngine.prototype.setIntArray = function (uniform, array) {
  87827. };
  87828. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  87829. };
  87830. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  87831. };
  87832. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  87833. };
  87834. NullEngine.prototype.setFloatArray = function (uniform, array) {
  87835. };
  87836. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  87837. };
  87838. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  87839. };
  87840. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  87841. };
  87842. NullEngine.prototype.setArray = function (uniform, array) {
  87843. };
  87844. NullEngine.prototype.setArray2 = function (uniform, array) {
  87845. };
  87846. NullEngine.prototype.setArray3 = function (uniform, array) {
  87847. };
  87848. NullEngine.prototype.setArray4 = function (uniform, array) {
  87849. };
  87850. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  87851. };
  87852. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  87853. };
  87854. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  87855. };
  87856. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  87857. };
  87858. NullEngine.prototype.setFloat = function (uniform, value) {
  87859. };
  87860. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  87861. };
  87862. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  87863. };
  87864. NullEngine.prototype.setBool = function (uniform, bool) {
  87865. };
  87866. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  87867. };
  87868. NullEngine.prototype.setColor3 = function (uniform, color3) {
  87869. };
  87870. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  87871. };
  87872. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  87873. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  87874. if (this._alphaMode === mode) {
  87875. return;
  87876. }
  87877. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  87878. if (!noDepthWriteChange) {
  87879. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  87880. }
  87881. this._alphaMode = mode;
  87882. };
  87883. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  87884. };
  87885. NullEngine.prototype.wipeCaches = function (bruteForce) {
  87886. if (this.preventCacheWipeBetweenFrames) {
  87887. return;
  87888. }
  87889. this.resetTextureCache();
  87890. this._currentEffect = null;
  87891. if (bruteForce) {
  87892. this._currentProgram = null;
  87893. this._stencilState.reset();
  87894. this._depthCullingState.reset();
  87895. this._alphaState.reset();
  87896. }
  87897. this._cachedVertexBuffers = null;
  87898. this._cachedIndexBuffer = null;
  87899. this._cachedEffectForVertexBuffers = null;
  87900. };
  87901. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  87902. };
  87903. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  87904. };
  87905. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  87906. };
  87907. NullEngine.prototype._createTexture = function () {
  87908. return {};
  87909. };
  87910. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  87911. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  87912. if (onLoad === void 0) { onLoad = null; }
  87913. if (onError === void 0) { onError = null; }
  87914. if (buffer === void 0) { buffer = null; }
  87915. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  87916. var url = String(urlArg);
  87917. texture.url = url;
  87918. texture.generateMipMaps = !noMipmap;
  87919. texture.samplingMode = samplingMode;
  87920. texture.invertY = invertY;
  87921. texture.baseWidth = this._options.textureSize;
  87922. texture.baseHeight = this._options.textureSize;
  87923. texture.width = this._options.textureSize;
  87924. texture.height = this._options.textureSize;
  87925. if (format) {
  87926. texture.format = format;
  87927. }
  87928. texture.isReady = true;
  87929. if (onLoad) {
  87930. onLoad();
  87931. }
  87932. return texture;
  87933. };
  87934. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  87935. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  87936. if (options !== undefined && typeof options === "object") {
  87937. fullOptions.generateMipMaps = options.generateMipMaps;
  87938. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  87939. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  87940. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  87941. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  87942. }
  87943. else {
  87944. fullOptions.generateMipMaps = options;
  87945. fullOptions.generateDepthBuffer = true;
  87946. fullOptions.generateStencilBuffer = false;
  87947. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87948. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  87949. }
  87950. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  87951. var width = size.width || size;
  87952. var height = size.height || size;
  87953. texture._depthStencilBuffer = {};
  87954. texture._framebuffer = {};
  87955. texture.baseWidth = width;
  87956. texture.baseHeight = height;
  87957. texture.width = width;
  87958. texture.height = height;
  87959. texture.isReady = true;
  87960. texture.samples = 1;
  87961. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  87962. texture.samplingMode = fullOptions.samplingMode;
  87963. texture.type = fullOptions.type;
  87964. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  87965. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  87966. return texture;
  87967. };
  87968. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  87969. texture.samplingMode = samplingMode;
  87970. };
  87971. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  87972. if (this._currentRenderTarget) {
  87973. this.unBindFramebuffer(this._currentRenderTarget);
  87974. }
  87975. this._currentRenderTarget = texture;
  87976. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  87977. if (this._cachedViewport && !forceFullscreenViewport) {
  87978. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  87979. }
  87980. };
  87981. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  87982. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  87983. this._currentRenderTarget = null;
  87984. if (onBeforeUnbind) {
  87985. if (texture._MSAAFramebuffer) {
  87986. this._currentFramebuffer = texture._framebuffer;
  87987. }
  87988. onBeforeUnbind();
  87989. }
  87990. this._currentFramebuffer = null;
  87991. };
  87992. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  87993. var vbo = {
  87994. capacity: 1,
  87995. references: 1,
  87996. is32Bits: false
  87997. };
  87998. return vbo;
  87999. };
  88000. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  88001. if (offset === void 0) { offset = 0; }
  88002. };
  88003. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  88004. };
  88005. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  88006. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  88007. this._boundTexturesCache[this._activeChannel] = texture;
  88008. }
  88009. };
  88010. NullEngine.prototype._bindTexture = function (channel, texture) {
  88011. if (channel < 0) {
  88012. return;
  88013. }
  88014. this._bindTextureDirectly(0, texture);
  88015. };
  88016. NullEngine.prototype._releaseBuffer = function (buffer) {
  88017. buffer.references--;
  88018. if (buffer.references === 0) {
  88019. return true;
  88020. }
  88021. return false;
  88022. };
  88023. return NullEngine;
  88024. }(BABYLON.Engine));
  88025. BABYLON.NullEngine = NullEngine;
  88026. })(BABYLON || (BABYLON = {}));
  88027. //# sourceMappingURL=babylon.nullEngine.js.map
  88028. var BABYLON;
  88029. (function (BABYLON) {
  88030. /**
  88031. * This class can be used to get instrumentation data from a Babylon engine
  88032. */
  88033. var EngineInstrumentation = /** @class */ (function () {
  88034. function EngineInstrumentation(engine) {
  88035. this.engine = engine;
  88036. this._captureGPUFrameTime = false;
  88037. this._gpuFrameTime = new BABYLON.PerfCounter();
  88038. this._captureShaderCompilationTime = false;
  88039. this._shaderCompilationTime = new BABYLON.PerfCounter();
  88040. // Observers
  88041. this._onBeginFrameObserver = null;
  88042. this._onEndFrameObserver = null;
  88043. this._onBeforeShaderCompilationObserver = null;
  88044. this._onAfterShaderCompilationObserver = null;
  88045. }
  88046. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  88047. // Properties
  88048. /**
  88049. * Gets the perf counter used for GPU frame time
  88050. */
  88051. get: function () {
  88052. return this._gpuFrameTime;
  88053. },
  88054. enumerable: true,
  88055. configurable: true
  88056. });
  88057. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  88058. /**
  88059. * Gets the GPU frame time capture status
  88060. */
  88061. get: function () {
  88062. return this._captureGPUFrameTime;
  88063. },
  88064. /**
  88065. * Enable or disable the GPU frame time capture
  88066. */
  88067. set: function (value) {
  88068. var _this = this;
  88069. if (value === this._captureGPUFrameTime) {
  88070. return;
  88071. }
  88072. this._captureGPUFrameTime = value;
  88073. if (value) {
  88074. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  88075. if (!_this._gpuFrameTimeToken) {
  88076. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  88077. }
  88078. });
  88079. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  88080. if (!_this._gpuFrameTimeToken) {
  88081. return;
  88082. }
  88083. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  88084. if (time > -1) {
  88085. _this._gpuFrameTimeToken = null;
  88086. _this._gpuFrameTime.fetchNewFrame();
  88087. _this._gpuFrameTime.addCount(time, true);
  88088. }
  88089. });
  88090. }
  88091. else {
  88092. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  88093. this._onBeginFrameObserver = null;
  88094. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  88095. this._onEndFrameObserver = null;
  88096. }
  88097. },
  88098. enumerable: true,
  88099. configurable: true
  88100. });
  88101. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  88102. /**
  88103. * Gets the perf counter used for shader compilation time
  88104. */
  88105. get: function () {
  88106. return this._shaderCompilationTime;
  88107. },
  88108. enumerable: true,
  88109. configurable: true
  88110. });
  88111. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  88112. /**
  88113. * Gets the shader compilation time capture status
  88114. */
  88115. get: function () {
  88116. return this._captureShaderCompilationTime;
  88117. },
  88118. /**
  88119. * Enable or disable the shader compilation time capture
  88120. */
  88121. set: function (value) {
  88122. var _this = this;
  88123. if (value === this._captureShaderCompilationTime) {
  88124. return;
  88125. }
  88126. this._captureShaderCompilationTime = value;
  88127. if (value) {
  88128. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  88129. _this._shaderCompilationTime.fetchNewFrame();
  88130. _this._shaderCompilationTime.beginMonitoring();
  88131. });
  88132. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  88133. _this._shaderCompilationTime.endMonitoring();
  88134. });
  88135. }
  88136. else {
  88137. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  88138. this._onBeforeShaderCompilationObserver = null;
  88139. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  88140. this._onAfterShaderCompilationObserver = null;
  88141. }
  88142. },
  88143. enumerable: true,
  88144. configurable: true
  88145. });
  88146. EngineInstrumentation.prototype.dispose = function () {
  88147. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  88148. this._onBeginFrameObserver = null;
  88149. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  88150. this._onEndFrameObserver = null;
  88151. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  88152. this._onBeforeShaderCompilationObserver = null;
  88153. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  88154. this._onAfterShaderCompilationObserver = null;
  88155. this.engine = null;
  88156. };
  88157. return EngineInstrumentation;
  88158. }());
  88159. BABYLON.EngineInstrumentation = EngineInstrumentation;
  88160. })(BABYLON || (BABYLON = {}));
  88161. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  88162. var BABYLON;
  88163. (function (BABYLON) {
  88164. /**
  88165. * This class can be used to get instrumentation data from a Babylon engine
  88166. */
  88167. var SceneInstrumentation = /** @class */ (function () {
  88168. function SceneInstrumentation(scene) {
  88169. var _this = this;
  88170. this.scene = scene;
  88171. this._captureActiveMeshesEvaluationTime = false;
  88172. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  88173. this._captureRenderTargetsRenderTime = false;
  88174. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  88175. this._captureFrameTime = false;
  88176. this._frameTime = new BABYLON.PerfCounter();
  88177. this._captureRenderTime = false;
  88178. this._renderTime = new BABYLON.PerfCounter();
  88179. this._captureInterFrameTime = false;
  88180. this._interFrameTime = new BABYLON.PerfCounter();
  88181. this._captureParticlesRenderTime = false;
  88182. this._particlesRenderTime = new BABYLON.PerfCounter();
  88183. this._captureSpritesRenderTime = false;
  88184. this._spritesRenderTime = new BABYLON.PerfCounter();
  88185. this._capturePhysicsTime = false;
  88186. this._physicsTime = new BABYLON.PerfCounter();
  88187. this._captureAnimationsTime = false;
  88188. this._animationsTime = new BABYLON.PerfCounter();
  88189. // Observers
  88190. this._onBeforeActiveMeshesEvaluationObserver = null;
  88191. this._onAfterActiveMeshesEvaluationObserver = null;
  88192. this._onBeforeRenderTargetsRenderObserver = null;
  88193. this._onAfterRenderTargetsRenderObserver = null;
  88194. this._onAfterRenderObserver = null;
  88195. this._onBeforeDrawPhaseObserver = null;
  88196. this._onAfterDrawPhaseObserver = null;
  88197. this._onBeforeAnimationsObserver = null;
  88198. this._onBeforeParticlesRenderingObserver = null;
  88199. this._onAfterParticlesRenderingObserver = null;
  88200. this._onBeforeSpritesRenderingObserver = null;
  88201. this._onAfterSpritesRenderingObserver = null;
  88202. this._onBeforePhysicsObserver = null;
  88203. this._onAfterPhysicsObserver = null;
  88204. this._onAfterAnimationsObserver = null;
  88205. // Before render
  88206. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  88207. if (_this._captureActiveMeshesEvaluationTime) {
  88208. _this._activeMeshesEvaluationTime.fetchNewFrame();
  88209. }
  88210. if (_this._captureRenderTargetsRenderTime) {
  88211. _this._renderTargetsRenderTime.fetchNewFrame();
  88212. }
  88213. if (_this._captureFrameTime) {
  88214. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  88215. _this._frameTime.beginMonitoring();
  88216. }
  88217. if (_this._captureInterFrameTime) {
  88218. _this._interFrameTime.endMonitoring();
  88219. }
  88220. if (_this._captureParticlesRenderTime) {
  88221. _this._particlesRenderTime.fetchNewFrame();
  88222. }
  88223. if (_this._captureSpritesRenderTime) {
  88224. _this._spritesRenderTime.fetchNewFrame();
  88225. }
  88226. if (_this._captureAnimationsTime) {
  88227. _this._animationsTime.beginMonitoring();
  88228. }
  88229. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  88230. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  88231. });
  88232. // After render
  88233. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  88234. if (_this._captureFrameTime) {
  88235. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  88236. _this._frameTime.endMonitoring();
  88237. }
  88238. if (_this._captureRenderTime) {
  88239. _this._renderTime.endMonitoring(false);
  88240. }
  88241. if (_this._captureInterFrameTime) {
  88242. _this._interFrameTime.beginMonitoring();
  88243. }
  88244. });
  88245. }
  88246. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  88247. // Properties
  88248. /**
  88249. * Gets the perf counter used for active meshes evaluation time
  88250. */
  88251. get: function () {
  88252. return this._activeMeshesEvaluationTime;
  88253. },
  88254. enumerable: true,
  88255. configurable: true
  88256. });
  88257. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  88258. /**
  88259. * Gets the active meshes evaluation time capture status
  88260. */
  88261. get: function () {
  88262. return this._captureActiveMeshesEvaluationTime;
  88263. },
  88264. /**
  88265. * Enable or disable the active meshes evaluation time capture
  88266. */
  88267. set: function (value) {
  88268. var _this = this;
  88269. if (value === this._captureActiveMeshesEvaluationTime) {
  88270. return;
  88271. }
  88272. this._captureActiveMeshesEvaluationTime = value;
  88273. if (value) {
  88274. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  88275. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  88276. _this._activeMeshesEvaluationTime.beginMonitoring();
  88277. });
  88278. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  88279. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  88280. _this._activeMeshesEvaluationTime.endMonitoring();
  88281. });
  88282. }
  88283. else {
  88284. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  88285. this._onBeforeActiveMeshesEvaluationObserver = null;
  88286. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  88287. this._onAfterActiveMeshesEvaluationObserver = null;
  88288. }
  88289. },
  88290. enumerable: true,
  88291. configurable: true
  88292. });
  88293. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  88294. /**
  88295. * Gets the perf counter used for render targets render time
  88296. */
  88297. get: function () {
  88298. return this._renderTargetsRenderTime;
  88299. },
  88300. enumerable: true,
  88301. configurable: true
  88302. });
  88303. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  88304. /**
  88305. * Gets the render targets render time capture status
  88306. */
  88307. get: function () {
  88308. return this._captureRenderTargetsRenderTime;
  88309. },
  88310. /**
  88311. * Enable or disable the render targets render time capture
  88312. */
  88313. set: function (value) {
  88314. var _this = this;
  88315. if (value === this._captureRenderTargetsRenderTime) {
  88316. return;
  88317. }
  88318. this._captureRenderTargetsRenderTime = value;
  88319. if (value) {
  88320. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  88321. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  88322. _this._renderTargetsRenderTime.beginMonitoring();
  88323. });
  88324. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  88325. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  88326. _this._renderTargetsRenderTime.endMonitoring(false);
  88327. });
  88328. }
  88329. else {
  88330. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  88331. this._onBeforeRenderTargetsRenderObserver = null;
  88332. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  88333. this._onAfterRenderTargetsRenderObserver = null;
  88334. }
  88335. },
  88336. enumerable: true,
  88337. configurable: true
  88338. });
  88339. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  88340. /**
  88341. * Gets the perf counter used for particles render time
  88342. */
  88343. get: function () {
  88344. return this._particlesRenderTime;
  88345. },
  88346. enumerable: true,
  88347. configurable: true
  88348. });
  88349. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  88350. /**
  88351. * Gets the particles render time capture status
  88352. */
  88353. get: function () {
  88354. return this._captureParticlesRenderTime;
  88355. },
  88356. /**
  88357. * Enable or disable the particles render time capture
  88358. */
  88359. set: function (value) {
  88360. var _this = this;
  88361. if (value === this._captureParticlesRenderTime) {
  88362. return;
  88363. }
  88364. this._captureParticlesRenderTime = value;
  88365. if (value) {
  88366. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  88367. BABYLON.Tools.StartPerformanceCounter("Particles");
  88368. _this._particlesRenderTime.beginMonitoring();
  88369. });
  88370. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  88371. BABYLON.Tools.EndPerformanceCounter("Particles");
  88372. _this._particlesRenderTime.endMonitoring(false);
  88373. });
  88374. }
  88375. else {
  88376. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  88377. this._onBeforeParticlesRenderingObserver = null;
  88378. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  88379. this._onAfterParticlesRenderingObserver = null;
  88380. }
  88381. },
  88382. enumerable: true,
  88383. configurable: true
  88384. });
  88385. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  88386. /**
  88387. * Gets the perf counter used for sprites render time
  88388. */
  88389. get: function () {
  88390. return this._spritesRenderTime;
  88391. },
  88392. enumerable: true,
  88393. configurable: true
  88394. });
  88395. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  88396. /**
  88397. * Gets the sprites render time capture status
  88398. */
  88399. get: function () {
  88400. return this._captureSpritesRenderTime;
  88401. },
  88402. /**
  88403. * Enable or disable the sprites render time capture
  88404. */
  88405. set: function (value) {
  88406. var _this = this;
  88407. if (value === this._captureSpritesRenderTime) {
  88408. return;
  88409. }
  88410. this._captureSpritesRenderTime = value;
  88411. if (value) {
  88412. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  88413. BABYLON.Tools.StartPerformanceCounter("Sprites");
  88414. _this._spritesRenderTime.beginMonitoring();
  88415. });
  88416. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  88417. BABYLON.Tools.EndPerformanceCounter("Sprites");
  88418. _this._spritesRenderTime.endMonitoring(false);
  88419. });
  88420. }
  88421. else {
  88422. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  88423. this._onBeforeSpritesRenderingObserver = null;
  88424. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  88425. this._onAfterSpritesRenderingObserver = null;
  88426. }
  88427. },
  88428. enumerable: true,
  88429. configurable: true
  88430. });
  88431. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  88432. /**
  88433. * Gets the perf counter used for physics time
  88434. */
  88435. get: function () {
  88436. return this._physicsTime;
  88437. },
  88438. enumerable: true,
  88439. configurable: true
  88440. });
  88441. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  88442. /**
  88443. * Gets the physics time capture status
  88444. */
  88445. get: function () {
  88446. return this._capturePhysicsTime;
  88447. },
  88448. /**
  88449. * Enable or disable the physics time capture
  88450. */
  88451. set: function (value) {
  88452. var _this = this;
  88453. if (value === this._capturePhysicsTime) {
  88454. return;
  88455. }
  88456. this._capturePhysicsTime = value;
  88457. if (value) {
  88458. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  88459. BABYLON.Tools.StartPerformanceCounter("Physics");
  88460. _this._physicsTime.beginMonitoring();
  88461. });
  88462. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  88463. BABYLON.Tools.EndPerformanceCounter("Physics");
  88464. _this._physicsTime.endMonitoring();
  88465. });
  88466. }
  88467. else {
  88468. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  88469. this._onBeforePhysicsObserver = null;
  88470. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  88471. this._onAfterPhysicsObserver = null;
  88472. }
  88473. },
  88474. enumerable: true,
  88475. configurable: true
  88476. });
  88477. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  88478. /**
  88479. * Gets the perf counter used for animations time
  88480. */
  88481. get: function () {
  88482. return this._animationsTime;
  88483. },
  88484. enumerable: true,
  88485. configurable: true
  88486. });
  88487. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  88488. /**
  88489. * Gets the animations time capture status
  88490. */
  88491. get: function () {
  88492. return this._captureAnimationsTime;
  88493. },
  88494. /**
  88495. * Enable or disable the animations time capture
  88496. */
  88497. set: function (value) {
  88498. var _this = this;
  88499. if (value === this._captureAnimationsTime) {
  88500. return;
  88501. }
  88502. this._captureAnimationsTime = value;
  88503. if (value) {
  88504. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  88505. _this._animationsTime.endMonitoring();
  88506. });
  88507. }
  88508. else {
  88509. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  88510. this._onAfterAnimationsObserver = null;
  88511. }
  88512. },
  88513. enumerable: true,
  88514. configurable: true
  88515. });
  88516. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  88517. /**
  88518. * Gets the perf counter used for frame time capture
  88519. */
  88520. get: function () {
  88521. return this._frameTime;
  88522. },
  88523. enumerable: true,
  88524. configurable: true
  88525. });
  88526. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  88527. /**
  88528. * Gets the frame time capture status
  88529. */
  88530. get: function () {
  88531. return this._captureFrameTime;
  88532. },
  88533. /**
  88534. * Enable or disable the frame time capture
  88535. */
  88536. set: function (value) {
  88537. this._captureFrameTime = value;
  88538. },
  88539. enumerable: true,
  88540. configurable: true
  88541. });
  88542. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  88543. /**
  88544. * Gets the perf counter used for inter-frames time capture
  88545. */
  88546. get: function () {
  88547. return this._interFrameTime;
  88548. },
  88549. enumerable: true,
  88550. configurable: true
  88551. });
  88552. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  88553. /**
  88554. * Gets the inter-frames time capture status
  88555. */
  88556. get: function () {
  88557. return this._captureInterFrameTime;
  88558. },
  88559. /**
  88560. * Enable or disable the inter-frames time capture
  88561. */
  88562. set: function (value) {
  88563. this._captureInterFrameTime = value;
  88564. },
  88565. enumerable: true,
  88566. configurable: true
  88567. });
  88568. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  88569. /**
  88570. * Gets the perf counter used for render time capture
  88571. */
  88572. get: function () {
  88573. return this._renderTime;
  88574. },
  88575. enumerable: true,
  88576. configurable: true
  88577. });
  88578. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  88579. /**
  88580. * Gets the render time capture status
  88581. */
  88582. get: function () {
  88583. return this._captureRenderTime;
  88584. },
  88585. /**
  88586. * Enable or disable the render time capture
  88587. */
  88588. set: function (value) {
  88589. var _this = this;
  88590. if (value === this._captureRenderTime) {
  88591. return;
  88592. }
  88593. this._captureRenderTime = value;
  88594. if (value) {
  88595. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  88596. _this._renderTime.beginMonitoring();
  88597. BABYLON.Tools.StartPerformanceCounter("Main render");
  88598. });
  88599. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  88600. _this._renderTime.endMonitoring(false);
  88601. BABYLON.Tools.EndPerformanceCounter("Main render");
  88602. });
  88603. }
  88604. else {
  88605. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  88606. this._onBeforeDrawPhaseObserver = null;
  88607. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  88608. this._onAfterDrawPhaseObserver = null;
  88609. }
  88610. },
  88611. enumerable: true,
  88612. configurable: true
  88613. });
  88614. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  88615. /**
  88616. * Gets the perf counter used for draw calls
  88617. */
  88618. get: function () {
  88619. return this.scene.getEngine()._drawCalls;
  88620. },
  88621. enumerable: true,
  88622. configurable: true
  88623. });
  88624. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  88625. /**
  88626. * Gets the perf counter used for texture collisions
  88627. */
  88628. get: function () {
  88629. return this.scene.getEngine()._textureCollisions;
  88630. },
  88631. enumerable: true,
  88632. configurable: true
  88633. });
  88634. SceneInstrumentation.prototype.dispose = function () {
  88635. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  88636. this._onAfterRenderObserver = null;
  88637. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  88638. this._onBeforeActiveMeshesEvaluationObserver = null;
  88639. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  88640. this._onAfterActiveMeshesEvaluationObserver = null;
  88641. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  88642. this._onBeforeRenderTargetsRenderObserver = null;
  88643. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  88644. this._onAfterRenderTargetsRenderObserver = null;
  88645. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  88646. this._onBeforeAnimationsObserver = null;
  88647. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  88648. this._onBeforeParticlesRenderingObserver = null;
  88649. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  88650. this._onAfterParticlesRenderingObserver = null;
  88651. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  88652. this._onBeforeSpritesRenderingObserver = null;
  88653. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  88654. this._onAfterSpritesRenderingObserver = null;
  88655. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  88656. this._onBeforeDrawPhaseObserver = null;
  88657. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  88658. this._onAfterDrawPhaseObserver = null;
  88659. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  88660. this._onBeforePhysicsObserver = null;
  88661. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  88662. this._onAfterPhysicsObserver = null;
  88663. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  88664. this._onAfterAnimationsObserver = null;
  88665. this.scene = null;
  88666. };
  88667. return SceneInstrumentation;
  88668. }());
  88669. BABYLON.SceneInstrumentation = SceneInstrumentation;
  88670. })(BABYLON || (BABYLON = {}));
  88671. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  88672. var BABYLON;
  88673. (function (BABYLON) {
  88674. var _TimeToken = /** @class */ (function () {
  88675. function _TimeToken() {
  88676. this._timeElapsedQueryEnded = false;
  88677. }
  88678. return _TimeToken;
  88679. }());
  88680. BABYLON._TimeToken = _TimeToken;
  88681. })(BABYLON || (BABYLON = {}));
  88682. //# sourceMappingURL=babylon.timeToken.js.map
  88683. var BABYLON;
  88684. (function (BABYLON) {
  88685. /**
  88686. * Background material defines definition.
  88687. * @ignore Mainly internal Use
  88688. */
  88689. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  88690. __extends(BackgroundMaterialDefines, _super);
  88691. /**
  88692. * Constructor of the defines.
  88693. */
  88694. function BackgroundMaterialDefines() {
  88695. var _this = _super.call(this) || this;
  88696. /**
  88697. * True if the diffuse texture is in use.
  88698. */
  88699. _this.DIFFUSE = false;
  88700. /**
  88701. * The direct UV channel to use.
  88702. */
  88703. _this.DIFFUSEDIRECTUV = 0;
  88704. /**
  88705. * True if the diffuse texture is in gamma space.
  88706. */
  88707. _this.GAMMADIFFUSE = false;
  88708. /**
  88709. * True if the diffuse texture has opacity in the alpha channel.
  88710. */
  88711. _this.DIFFUSEHASALPHA = false;
  88712. /**
  88713. * True if you want the material to fade to transparent at grazing angle.
  88714. */
  88715. _this.OPACITYFRESNEL = false;
  88716. /**
  88717. * True if an extra blur needs to be added in the reflection.
  88718. */
  88719. _this.REFLECTIONBLUR = false;
  88720. /**
  88721. * True if you want the material to fade to reflection at grazing angle.
  88722. */
  88723. _this.REFLECTIONFRESNEL = false;
  88724. /**
  88725. * True if you want the material to falloff as far as you move away from the scene center.
  88726. */
  88727. _this.REFLECTIONFALLOFF = false;
  88728. /**
  88729. * False if the current Webgl implementation does not support the texture lod extension.
  88730. */
  88731. _this.TEXTURELODSUPPORT = false;
  88732. /**
  88733. * True to ensure the data are premultiplied.
  88734. */
  88735. _this.PREMULTIPLYALPHA = false;
  88736. /**
  88737. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  88738. */
  88739. _this.USERGBCOLOR = false;
  88740. /**
  88741. * True to add noise in order to reduce the banding effect.
  88742. */
  88743. _this.NOISE = false;
  88744. /**
  88745. * is the reflection texture in BGR color scheme?
  88746. * Mainly used to solve a bug in ios10 video tag
  88747. */
  88748. _this.REFLECTIONBGR = false;
  88749. _this.IMAGEPROCESSING = false;
  88750. _this.VIGNETTE = false;
  88751. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  88752. _this.VIGNETTEBLENDMODEOPAQUE = false;
  88753. _this.TONEMAPPING = false;
  88754. _this.CONTRAST = false;
  88755. _this.COLORCURVES = false;
  88756. _this.COLORGRADING = false;
  88757. _this.COLORGRADING3D = false;
  88758. _this.SAMPLER3DGREENDEPTH = false;
  88759. _this.SAMPLER3DBGRMAP = false;
  88760. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  88761. _this.EXPOSURE = false;
  88762. // Reflection.
  88763. _this.REFLECTION = false;
  88764. _this.REFLECTIONMAP_3D = false;
  88765. _this.REFLECTIONMAP_SPHERICAL = false;
  88766. _this.REFLECTIONMAP_PLANAR = false;
  88767. _this.REFLECTIONMAP_CUBIC = false;
  88768. _this.REFLECTIONMAP_PROJECTION = false;
  88769. _this.REFLECTIONMAP_SKYBOX = false;
  88770. _this.REFLECTIONMAP_EXPLICIT = false;
  88771. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  88772. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  88773. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  88774. _this.INVERTCUBICMAP = false;
  88775. _this.REFLECTIONMAP_OPPOSITEZ = false;
  88776. _this.LODINREFLECTIONALPHA = false;
  88777. _this.GAMMAREFLECTION = false;
  88778. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  88779. // Default BJS.
  88780. _this.MAINUV1 = false;
  88781. _this.MAINUV2 = false;
  88782. _this.UV1 = false;
  88783. _this.UV2 = false;
  88784. _this.CLIPPLANE = false;
  88785. _this.POINTSIZE = false;
  88786. _this.FOG = false;
  88787. _this.NORMAL = false;
  88788. _this.NUM_BONE_INFLUENCERS = 0;
  88789. _this.BonesPerMesh = 0;
  88790. _this.INSTANCES = false;
  88791. _this.SHADOWFLOAT = false;
  88792. _this.rebuild();
  88793. return _this;
  88794. }
  88795. return BackgroundMaterialDefines;
  88796. }(BABYLON.MaterialDefines));
  88797. /**
  88798. * Background material used to create an efficient environement around your scene.
  88799. */
  88800. var BackgroundMaterial = /** @class */ (function (_super) {
  88801. __extends(BackgroundMaterial, _super);
  88802. /**
  88803. * Instantiates a Background Material in the given scene
  88804. * @param name The friendly name of the material
  88805. * @param scene The scene to add the material to
  88806. */
  88807. function BackgroundMaterial(name, scene) {
  88808. var _this = _super.call(this, name, scene) || this;
  88809. /**
  88810. * Key light Color (multiply against the R channel of the environement texture)
  88811. */
  88812. _this.primaryColor = BABYLON.Color3.White();
  88813. /**
  88814. * Key light Level (allowing HDR output of the background)
  88815. */
  88816. _this.primaryLevel = 1;
  88817. /**
  88818. * Secondary light Color (multiply against the G channel of the environement texture)
  88819. */
  88820. _this.secondaryColor = BABYLON.Color3.Gray();
  88821. /**
  88822. * Secondary light Level (allowing HDR output of the background)
  88823. */
  88824. _this.secondaryLevel = 1;
  88825. /**
  88826. * Tertiary light Color (multiply against the B channel of the environement texture)
  88827. */
  88828. _this.tertiaryColor = BABYLON.Color3.Black();
  88829. /**
  88830. * Tertiary light Level (allowing HDR output of the background)
  88831. */
  88832. _this.tertiaryLevel = 1;
  88833. /**
  88834. * Reflection Texture used in the material.
  88835. * Should be author in a specific way for the best result (refer to the documentation).
  88836. */
  88837. _this.reflectionTexture = null;
  88838. /**
  88839. * Reflection Texture level of blur.
  88840. *
  88841. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  88842. * texture twice.
  88843. */
  88844. _this.reflectionBlur = 0;
  88845. /**
  88846. * Diffuse Texture used in the material.
  88847. * Should be author in a specific way for the best result (refer to the documentation).
  88848. */
  88849. _this.diffuseTexture = null;
  88850. _this._shadowLights = null;
  88851. /**
  88852. * Specify the list of lights casting shadow on the material.
  88853. * All scene shadow lights will be included if null.
  88854. */
  88855. _this.shadowLights = null;
  88856. /**
  88857. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  88858. * soft lighting on the background.
  88859. */
  88860. _this.shadowBlurScale = 1;
  88861. /**
  88862. * Helps adjusting the shadow to a softer level if required.
  88863. * 0 means black shadows and 1 means no shadows.
  88864. */
  88865. _this.shadowLevel = 0;
  88866. /**
  88867. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  88868. * It is usually zero but might be interesting to modify according to your setup.
  88869. */
  88870. _this.sceneCenter = BABYLON.Vector3.Zero();
  88871. /**
  88872. * This helps specifying that the material is falling off to the sky box at grazing angle.
  88873. * This helps ensuring a nice transition when the camera goes under the ground.
  88874. */
  88875. _this.opacityFresnel = true;
  88876. /**
  88877. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  88878. * This helps adding a mirror texture on the ground.
  88879. */
  88880. _this.reflectionFresnel = false;
  88881. /**
  88882. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  88883. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  88884. */
  88885. _this.reflectionFalloffDistance = 0.0;
  88886. /**
  88887. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  88888. */
  88889. _this.reflectionAmount = 1.0;
  88890. /**
  88891. * This specifies the weight of the reflection at grazing angle.
  88892. */
  88893. _this.reflectionReflectance0 = 0.05;
  88894. /**
  88895. * This specifies the weight of the reflection at a perpendicular point of view.
  88896. */
  88897. _this.reflectionReflectance90 = 0.5;
  88898. /**
  88899. * Helps to directly use the maps channels instead of their level.
  88900. */
  88901. _this.useRGBColor = true;
  88902. /**
  88903. * This helps reducing the banding effect that could occur on the background.
  88904. */
  88905. _this.enableNoise = false;
  88906. _this._fovMultiplier = 1.0;
  88907. /**
  88908. * Enable the FOV adjustment feature controlled by fovMultiplier.
  88909. * @type {boolean}
  88910. */
  88911. _this.useEquirectangularFOV = false;
  88912. _this._maxSimultaneousLights = 4;
  88913. /**
  88914. * Number of Simultaneous lights allowed on the material.
  88915. */
  88916. _this.maxSimultaneousLights = 4;
  88917. /**
  88918. * Keep track of the image processing observer to allow dispose and replace.
  88919. */
  88920. _this._imageProcessingObserver = null;
  88921. /**
  88922. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  88923. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  88924. */
  88925. _this.switchToBGR = false;
  88926. // Temp values kept as cache in the material.
  88927. _this._renderTargets = new BABYLON.SmartArray(16);
  88928. _this._reflectionControls = BABYLON.Vector4.Zero();
  88929. // Setup the default processing configuration to the scene.
  88930. _this._attachImageProcessingConfiguration(null);
  88931. _this.getRenderTargetTextures = function () {
  88932. _this._renderTargets.reset();
  88933. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  88934. _this._renderTargets.push(_this._diffuseTexture);
  88935. }
  88936. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  88937. _this._renderTargets.push(_this._reflectionTexture);
  88938. }
  88939. return _this._renderTargets;
  88940. };
  88941. return _this;
  88942. }
  88943. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  88944. /**
  88945. * Sets the reflection reflectance fresnel values according to the default standard
  88946. * empirically know to work well :-)
  88947. */
  88948. set: function (value) {
  88949. var reflectionWeight = value;
  88950. if (reflectionWeight < 0.5) {
  88951. reflectionWeight = reflectionWeight * 2.0;
  88952. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  88953. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  88954. }
  88955. else {
  88956. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  88957. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  88958. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  88959. }
  88960. },
  88961. enumerable: true,
  88962. configurable: true
  88963. });
  88964. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  88965. /**
  88966. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  88967. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  88968. * Recommended to be keep at 1.0 except for special cases.
  88969. */
  88970. get: function () {
  88971. return this._fovMultiplier;
  88972. },
  88973. set: function (value) {
  88974. if (isNaN(value)) {
  88975. value = 1.0;
  88976. }
  88977. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  88978. },
  88979. enumerable: true,
  88980. configurable: true
  88981. });
  88982. /**
  88983. * Attaches a new image processing configuration to the PBR Material.
  88984. * @param configuration (if null the scene configuration will be use)
  88985. */
  88986. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  88987. var _this = this;
  88988. if (configuration === this._imageProcessingConfiguration) {
  88989. return;
  88990. }
  88991. // Detaches observer.
  88992. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  88993. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  88994. }
  88995. // Pick the scene configuration if needed.
  88996. if (!configuration) {
  88997. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  88998. }
  88999. else {
  89000. this._imageProcessingConfiguration = configuration;
  89001. }
  89002. // Attaches observer.
  89003. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  89004. _this._markAllSubMeshesAsImageProcessingDirty();
  89005. });
  89006. };
  89007. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  89008. /**
  89009. * Gets the image processing configuration used either in this material.
  89010. */
  89011. get: function () {
  89012. return this._imageProcessingConfiguration;
  89013. },
  89014. /**
  89015. * Sets the Default image processing configuration used either in the this material.
  89016. *
  89017. * If sets to null, the scene one is in use.
  89018. */
  89019. set: function (value) {
  89020. this._attachImageProcessingConfiguration(value);
  89021. // Ensure the effect will be rebuilt.
  89022. this._markAllSubMeshesAsTexturesDirty();
  89023. },
  89024. enumerable: true,
  89025. configurable: true
  89026. });
  89027. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  89028. /**
  89029. * Gets wether the color curves effect is enabled.
  89030. */
  89031. get: function () {
  89032. return this.imageProcessingConfiguration.colorCurvesEnabled;
  89033. },
  89034. /**
  89035. * Sets wether the color curves effect is enabled.
  89036. */
  89037. set: function (value) {
  89038. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  89039. },
  89040. enumerable: true,
  89041. configurable: true
  89042. });
  89043. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  89044. /**
  89045. * Gets wether the color grading effect is enabled.
  89046. */
  89047. get: function () {
  89048. return this.imageProcessingConfiguration.colorGradingEnabled;
  89049. },
  89050. /**
  89051. * Gets wether the color grading effect is enabled.
  89052. */
  89053. set: function (value) {
  89054. this.imageProcessingConfiguration.colorGradingEnabled = value;
  89055. },
  89056. enumerable: true,
  89057. configurable: true
  89058. });
  89059. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  89060. /**
  89061. * Gets wether tonemapping is enabled or not.
  89062. */
  89063. get: function () {
  89064. return this._imageProcessingConfiguration.toneMappingEnabled;
  89065. },
  89066. /**
  89067. * Sets wether tonemapping is enabled or not
  89068. */
  89069. set: function (value) {
  89070. this._imageProcessingConfiguration.toneMappingEnabled = value;
  89071. },
  89072. enumerable: true,
  89073. configurable: true
  89074. });
  89075. ;
  89076. ;
  89077. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  89078. /**
  89079. * The camera exposure used on this material.
  89080. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  89081. * This corresponds to a photographic exposure.
  89082. */
  89083. get: function () {
  89084. return this._imageProcessingConfiguration.exposure;
  89085. },
  89086. /**
  89087. * The camera exposure used on this material.
  89088. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  89089. * This corresponds to a photographic exposure.
  89090. */
  89091. set: function (value) {
  89092. this._imageProcessingConfiguration.exposure = value;
  89093. },
  89094. enumerable: true,
  89095. configurable: true
  89096. });
  89097. ;
  89098. ;
  89099. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  89100. /**
  89101. * Gets The camera contrast used on this material.
  89102. */
  89103. get: function () {
  89104. return this._imageProcessingConfiguration.contrast;
  89105. },
  89106. /**
  89107. * Sets The camera contrast used on this material.
  89108. */
  89109. set: function (value) {
  89110. this._imageProcessingConfiguration.contrast = value;
  89111. },
  89112. enumerable: true,
  89113. configurable: true
  89114. });
  89115. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  89116. /**
  89117. * Gets the Color Grading 2D Lookup Texture.
  89118. */
  89119. get: function () {
  89120. return this._imageProcessingConfiguration.colorGradingTexture;
  89121. },
  89122. /**
  89123. * Sets the Color Grading 2D Lookup Texture.
  89124. */
  89125. set: function (value) {
  89126. this.imageProcessingConfiguration.colorGradingTexture = value;
  89127. },
  89128. enumerable: true,
  89129. configurable: true
  89130. });
  89131. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  89132. /**
  89133. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  89134. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  89135. * 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;
  89136. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  89137. */
  89138. get: function () {
  89139. return this.imageProcessingConfiguration.colorCurves;
  89140. },
  89141. /**
  89142. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  89143. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  89144. * 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;
  89145. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  89146. */
  89147. set: function (value) {
  89148. this.imageProcessingConfiguration.colorCurves = value;
  89149. },
  89150. enumerable: true,
  89151. configurable: true
  89152. });
  89153. /**
  89154. * The entire material has been created in order to prevent overdraw.
  89155. * @returns false
  89156. */
  89157. BackgroundMaterial.prototype.needAlphaTesting = function () {
  89158. return true;
  89159. };
  89160. /**
  89161. * The entire material has been created in order to prevent overdraw.
  89162. * @returns true if blending is enable
  89163. */
  89164. BackgroundMaterial.prototype.needAlphaBlending = function () {
  89165. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  89166. };
  89167. /**
  89168. * Checks wether the material is ready to be rendered for a given mesh.
  89169. * @param mesh The mesh to render
  89170. * @param subMesh The submesh to check against
  89171. * @param useInstances Specify wether or not the material is used with instances
  89172. * @returns true if all the dependencies are ready (Textures, Effects...)
  89173. */
  89174. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  89175. var _this = this;
  89176. if (useInstances === void 0) { useInstances = false; }
  89177. if (subMesh.effect && this.isFrozen) {
  89178. if (this._wasPreviouslyReady) {
  89179. return true;
  89180. }
  89181. }
  89182. if (!subMesh._materialDefines) {
  89183. subMesh._materialDefines = new BackgroundMaterialDefines();
  89184. }
  89185. var scene = this.getScene();
  89186. var defines = subMesh._materialDefines;
  89187. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  89188. if (defines._renderId === scene.getRenderId()) {
  89189. return true;
  89190. }
  89191. }
  89192. var engine = scene.getEngine();
  89193. // Lights
  89194. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  89195. defines._needNormals = true;
  89196. // Textures
  89197. if (defines._areTexturesDirty) {
  89198. defines._needUVs = false;
  89199. if (scene.texturesEnabled) {
  89200. if (scene.getEngine().getCaps().textureLOD) {
  89201. defines.TEXTURELODSUPPORT = true;
  89202. }
  89203. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  89204. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  89205. return false;
  89206. }
  89207. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  89208. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  89209. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  89210. defines.OPACITYFRESNEL = this._opacityFresnel;
  89211. }
  89212. else {
  89213. defines.DIFFUSE = false;
  89214. defines.DIFFUSEHASALPHA = false;
  89215. defines.GAMMADIFFUSE = false;
  89216. defines.OPACITYFRESNEL = false;
  89217. }
  89218. var reflectionTexture = this._reflectionTexture;
  89219. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  89220. if (!reflectionTexture.isReadyOrNotBlocking()) {
  89221. return false;
  89222. }
  89223. defines.REFLECTION = true;
  89224. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  89225. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  89226. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  89227. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  89228. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  89229. defines.REFLECTIONBGR = this.switchToBGR;
  89230. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  89231. defines.INVERTCUBICMAP = true;
  89232. }
  89233. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  89234. switch (reflectionTexture.coordinatesMode) {
  89235. case BABYLON.Texture.CUBIC_MODE:
  89236. case BABYLON.Texture.INVCUBIC_MODE:
  89237. defines.REFLECTIONMAP_CUBIC = true;
  89238. break;
  89239. case BABYLON.Texture.EXPLICIT_MODE:
  89240. defines.REFLECTIONMAP_EXPLICIT = true;
  89241. break;
  89242. case BABYLON.Texture.PLANAR_MODE:
  89243. defines.REFLECTIONMAP_PLANAR = true;
  89244. break;
  89245. case BABYLON.Texture.PROJECTION_MODE:
  89246. defines.REFLECTIONMAP_PROJECTION = true;
  89247. break;
  89248. case BABYLON.Texture.SKYBOX_MODE:
  89249. defines.REFLECTIONMAP_SKYBOX = true;
  89250. break;
  89251. case BABYLON.Texture.SPHERICAL_MODE:
  89252. defines.REFLECTIONMAP_SPHERICAL = true;
  89253. break;
  89254. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  89255. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  89256. break;
  89257. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  89258. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  89259. break;
  89260. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  89261. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  89262. break;
  89263. }
  89264. if (this.reflectionFresnel) {
  89265. defines.REFLECTIONFRESNEL = true;
  89266. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  89267. this._reflectionControls.x = this.reflectionAmount;
  89268. this._reflectionControls.y = this.reflectionReflectance0;
  89269. this._reflectionControls.z = this.reflectionReflectance90;
  89270. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  89271. }
  89272. else {
  89273. defines.REFLECTIONFRESNEL = false;
  89274. defines.REFLECTIONFALLOFF = false;
  89275. }
  89276. }
  89277. else {
  89278. defines.REFLECTION = false;
  89279. defines.REFLECTIONFALLOFF = false;
  89280. defines.REFLECTIONBLUR = false;
  89281. defines.REFLECTIONMAP_3D = false;
  89282. defines.REFLECTIONMAP_SPHERICAL = false;
  89283. defines.REFLECTIONMAP_PLANAR = false;
  89284. defines.REFLECTIONMAP_CUBIC = false;
  89285. defines.REFLECTIONMAP_PROJECTION = false;
  89286. defines.REFLECTIONMAP_SKYBOX = false;
  89287. defines.REFLECTIONMAP_EXPLICIT = false;
  89288. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  89289. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  89290. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  89291. defines.INVERTCUBICMAP = false;
  89292. defines.REFLECTIONMAP_OPPOSITEZ = false;
  89293. defines.LODINREFLECTIONALPHA = false;
  89294. defines.GAMMAREFLECTION = false;
  89295. }
  89296. }
  89297. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  89298. defines.USERGBCOLOR = this._useRGBColor;
  89299. defines.NOISE = this._enableNoise;
  89300. }
  89301. if (defines._areImageProcessingDirty) {
  89302. if (!this._imageProcessingConfiguration.isReady()) {
  89303. return false;
  89304. }
  89305. this._imageProcessingConfiguration.prepareDefines(defines);
  89306. }
  89307. // Misc.
  89308. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  89309. // Values that need to be evaluated on every frame
  89310. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  89311. // Attribs
  89312. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  89313. if (mesh) {
  89314. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  89315. mesh.createNormals(true);
  89316. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  89317. }
  89318. }
  89319. }
  89320. // Get correct effect
  89321. if (defines.isDirty) {
  89322. defines.markAsProcessed();
  89323. scene.resetCachedMaterial();
  89324. // Fallbacks
  89325. var fallbacks = new BABYLON.EffectFallbacks();
  89326. if (defines.FOG) {
  89327. fallbacks.addFallback(0, "FOG");
  89328. }
  89329. if (defines.POINTSIZE) {
  89330. fallbacks.addFallback(1, "POINTSIZE");
  89331. }
  89332. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  89333. if (defines.NUM_BONE_INFLUENCERS > 0) {
  89334. fallbacks.addCPUSkinningFallback(0, mesh);
  89335. }
  89336. //Attributes
  89337. var attribs = [BABYLON.VertexBuffer.PositionKind];
  89338. if (defines.NORMAL) {
  89339. attribs.push(BABYLON.VertexBuffer.NormalKind);
  89340. }
  89341. if (defines.UV1) {
  89342. attribs.push(BABYLON.VertexBuffer.UVKind);
  89343. }
  89344. if (defines.UV2) {
  89345. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  89346. }
  89347. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  89348. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  89349. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  89350. "vFogInfos", "vFogColor", "pointSize",
  89351. "vClipPlane", "mBones",
  89352. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  89353. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  89354. "shadowLevel", "alpha",
  89355. "vBackgroundCenter", "vReflectionControl",
  89356. "vDiffuseInfos", "diffuseMatrix",
  89357. ];
  89358. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  89359. var uniformBuffers = ["Material", "Scene"];
  89360. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  89361. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  89362. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  89363. uniformsNames: uniforms,
  89364. uniformBuffersNames: uniformBuffers,
  89365. samplers: samplers,
  89366. defines: defines,
  89367. maxSimultaneousLights: this._maxSimultaneousLights
  89368. });
  89369. var onCompiled = function (effect) {
  89370. if (_this.onCompiled) {
  89371. _this.onCompiled(effect);
  89372. }
  89373. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  89374. };
  89375. var join = defines.toString();
  89376. subMesh.setEffect(scene.getEngine().createEffect("background", {
  89377. attributes: attribs,
  89378. uniformsNames: uniforms,
  89379. uniformBuffersNames: uniformBuffers,
  89380. samplers: samplers,
  89381. defines: join,
  89382. fallbacks: fallbacks,
  89383. onCompiled: onCompiled,
  89384. onError: this.onError,
  89385. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  89386. }, engine), defines);
  89387. this.buildUniformLayout();
  89388. }
  89389. if (!subMesh.effect || !subMesh.effect.isReady()) {
  89390. return false;
  89391. }
  89392. defines._renderId = scene.getRenderId();
  89393. this._wasPreviouslyReady = true;
  89394. return true;
  89395. };
  89396. /**
  89397. * Build the uniform buffer used in the material.
  89398. */
  89399. BackgroundMaterial.prototype.buildUniformLayout = function () {
  89400. // Order is important !
  89401. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  89402. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  89403. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  89404. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  89405. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  89406. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  89407. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  89408. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  89409. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  89410. this._uniformBuffer.addUniform("pointSize", 1);
  89411. this._uniformBuffer.addUniform("shadowLevel", 1);
  89412. this._uniformBuffer.addUniform("alpha", 1);
  89413. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  89414. this._uniformBuffer.addUniform("vReflectionControl", 4);
  89415. this._uniformBuffer.create();
  89416. };
  89417. /**
  89418. * Unbind the material.
  89419. */
  89420. BackgroundMaterial.prototype.unbind = function () {
  89421. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  89422. this._uniformBuffer.setTexture("diffuseSampler", null);
  89423. }
  89424. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  89425. this._uniformBuffer.setTexture("reflectionSampler", null);
  89426. }
  89427. _super.prototype.unbind.call(this);
  89428. };
  89429. /**
  89430. * Bind only the world matrix to the material.
  89431. * @param world The world matrix to bind.
  89432. */
  89433. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  89434. this._activeEffect.setMatrix("world", world);
  89435. };
  89436. /**
  89437. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  89438. * @param world The world matrix to bind.
  89439. * @param subMesh The submesh to bind for.
  89440. */
  89441. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  89442. var scene = this.getScene();
  89443. var defines = subMesh._materialDefines;
  89444. if (!defines) {
  89445. return;
  89446. }
  89447. var effect = subMesh.effect;
  89448. if (!effect) {
  89449. return;
  89450. }
  89451. this._activeEffect = effect;
  89452. // Matrices
  89453. this.bindOnlyWorldMatrix(world);
  89454. // Bones
  89455. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  89456. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  89457. if (mustRebind) {
  89458. this._uniformBuffer.bindToEffect(effect, "Material");
  89459. this.bindViewProjection(effect);
  89460. var reflectionTexture = this._reflectionTexture;
  89461. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  89462. // Texture uniforms
  89463. if (scene.texturesEnabled) {
  89464. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  89465. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  89466. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  89467. }
  89468. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  89469. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  89470. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  89471. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  89472. }
  89473. }
  89474. if (this.shadowLevel > 0) {
  89475. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  89476. }
  89477. this._uniformBuffer.updateFloat("alpha", this.alpha);
  89478. // Point size
  89479. if (this.pointsCloud) {
  89480. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  89481. }
  89482. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  89483. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  89484. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  89485. }
  89486. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  89487. // Textures
  89488. if (scene.texturesEnabled) {
  89489. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  89490. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  89491. }
  89492. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  89493. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  89494. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  89495. }
  89496. else if (!defines.REFLECTIONBLUR) {
  89497. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  89498. }
  89499. else {
  89500. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  89501. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  89502. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  89503. }
  89504. if (defines.REFLECTIONFRESNEL) {
  89505. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  89506. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  89507. }
  89508. }
  89509. }
  89510. // Clip plane
  89511. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  89512. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  89513. }
  89514. if (mustRebind || !this.isFrozen) {
  89515. if (scene.lightsEnabled) {
  89516. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  89517. }
  89518. // View
  89519. this.bindView(effect);
  89520. // Fog
  89521. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  89522. // image processing
  89523. this._imageProcessingConfiguration.bind(this._activeEffect);
  89524. }
  89525. this._uniformBuffer.update();
  89526. this._afterBind(mesh);
  89527. };
  89528. /**
  89529. * Dispose the material.
  89530. * @param forceDisposeEffect Force disposal of the associated effect.
  89531. * @param forceDisposeTextures Force disposal of the associated textures.
  89532. */
  89533. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  89534. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  89535. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  89536. if (forceDisposeTextures) {
  89537. if (this.diffuseTexture) {
  89538. this.diffuseTexture.dispose();
  89539. }
  89540. if (this.reflectionTexture) {
  89541. this.reflectionTexture.dispose();
  89542. }
  89543. }
  89544. this._renderTargets.dispose();
  89545. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  89546. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  89547. }
  89548. _super.prototype.dispose.call(this, forceDisposeEffect);
  89549. };
  89550. /**
  89551. * Clones the material.
  89552. * @param name The cloned name.
  89553. * @returns The cloned material.
  89554. */
  89555. BackgroundMaterial.prototype.clone = function (name) {
  89556. var _this = this;
  89557. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  89558. };
  89559. /**
  89560. * Serializes the current material to its JSON representation.
  89561. * @returns The JSON representation.
  89562. */
  89563. BackgroundMaterial.prototype.serialize = function () {
  89564. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  89565. serializationObject.customType = "BABYLON.BackgroundMaterial";
  89566. return serializationObject;
  89567. };
  89568. /**
  89569. * Gets the class name of the material
  89570. * @returns "BackgroundMaterial"
  89571. */
  89572. BackgroundMaterial.prototype.getClassName = function () {
  89573. return "BackgroundMaterial";
  89574. };
  89575. /**
  89576. * Parse a JSON input to create back a background material.
  89577. * @param source The JSON data to parse
  89578. * @param scene The scene to create the parsed material in
  89579. * @param rootUrl The root url of the assets the material depends upon
  89580. * @returns the instantiated BackgroundMaterial.
  89581. */
  89582. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  89583. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  89584. };
  89585. /**
  89586. * Standard reflectance value at parallel view angle.
  89587. */
  89588. BackgroundMaterial.StandardReflectance0 = 0.05;
  89589. /**
  89590. * Standard reflectance value at grazing angle.
  89591. */
  89592. BackgroundMaterial.StandardReflectance90 = 0.5;
  89593. __decorate([
  89594. BABYLON.serializeAsColor3()
  89595. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  89596. __decorate([
  89597. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89598. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  89599. __decorate([
  89600. BABYLON.serialize()
  89601. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  89602. __decorate([
  89603. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89604. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  89605. __decorate([
  89606. BABYLON.serializeAsColor3()
  89607. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  89608. __decorate([
  89609. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89610. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  89611. __decorate([
  89612. BABYLON.serialize()
  89613. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  89614. __decorate([
  89615. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89616. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  89617. __decorate([
  89618. BABYLON.serializeAsColor3()
  89619. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  89620. __decorate([
  89621. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89622. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  89623. __decorate([
  89624. BABYLON.serialize()
  89625. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  89626. __decorate([
  89627. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89628. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  89629. __decorate([
  89630. BABYLON.serializeAsTexture()
  89631. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  89632. __decorate([
  89633. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89634. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  89635. __decorate([
  89636. BABYLON.serialize()
  89637. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  89638. __decorate([
  89639. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89640. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  89641. __decorate([
  89642. BABYLON.serializeAsTexture()
  89643. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  89644. __decorate([
  89645. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89646. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  89647. __decorate([
  89648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89649. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  89650. __decorate([
  89651. BABYLON.serialize()
  89652. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  89653. __decorate([
  89654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89655. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  89656. __decorate([
  89657. BABYLON.serialize()
  89658. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  89659. __decorate([
  89660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89661. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  89662. __decorate([
  89663. BABYLON.serializeAsVector3()
  89664. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  89665. __decorate([
  89666. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89667. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  89668. __decorate([
  89669. BABYLON.serialize()
  89670. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  89671. __decorate([
  89672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89673. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  89674. __decorate([
  89675. BABYLON.serialize()
  89676. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  89677. __decorate([
  89678. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89679. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  89680. __decorate([
  89681. BABYLON.serialize()
  89682. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  89683. __decorate([
  89684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89685. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  89686. __decorate([
  89687. BABYLON.serialize()
  89688. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  89689. __decorate([
  89690. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89691. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  89692. __decorate([
  89693. BABYLON.serialize()
  89694. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  89695. __decorate([
  89696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89697. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  89698. __decorate([
  89699. BABYLON.serialize()
  89700. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  89701. __decorate([
  89702. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89703. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  89704. __decorate([
  89705. BABYLON.serialize()
  89706. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  89707. __decorate([
  89708. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89709. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  89710. __decorate([
  89711. BABYLON.serialize()
  89712. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  89713. __decorate([
  89714. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89715. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  89716. __decorate([
  89717. BABYLON.serialize()
  89718. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  89719. __decorate([
  89720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89721. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  89722. __decorate([
  89723. BABYLON.serializeAsImageProcessingConfiguration()
  89724. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  89725. return BackgroundMaterial;
  89726. }(BABYLON.PushMaterial));
  89727. BABYLON.BackgroundMaterial = BackgroundMaterial;
  89728. })(BABYLON || (BABYLON = {}));
  89729. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  89730. var __assign = (this && this.__assign) || Object.assign || function(t) {
  89731. for (var s, i = 1, n = arguments.length; i < n; i++) {
  89732. s = arguments[i];
  89733. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  89734. t[p] = s[p];
  89735. }
  89736. return t;
  89737. };
  89738. var BABYLON;
  89739. (function (BABYLON) {
  89740. /**
  89741. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  89742. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  89743. * It also helps with the default setup of your imageProcessing configuration.
  89744. */
  89745. var EnvironmentHelper = /** @class */ (function () {
  89746. /**
  89747. * constructor
  89748. * @param options
  89749. * @param scene The scene to add the material to
  89750. */
  89751. function EnvironmentHelper(options, scene) {
  89752. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  89753. this._scene = scene;
  89754. this._setupBackground();
  89755. this._setupImageProcessing();
  89756. }
  89757. /**
  89758. * Creates the default options for the helper.
  89759. */
  89760. EnvironmentHelper._getDefaultOptions = function () {
  89761. return {
  89762. createGround: true,
  89763. groundSize: 15,
  89764. groundTexture: this._groundTextureCDNUrl,
  89765. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  89766. groundOpacity: 0.9,
  89767. enableGroundShadow: true,
  89768. groundShadowLevel: 0.5,
  89769. enableGroundMirror: false,
  89770. groundMirrorSizeRatio: 0.3,
  89771. groundMirrorBlurKernel: 64,
  89772. groundMirrorAmount: 1,
  89773. groundMirrorFresnelWeight: 1,
  89774. groundMirrorFallOffDistance: 0,
  89775. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  89776. groundYBias: 0.00001,
  89777. createSkybox: true,
  89778. skyboxSize: 20,
  89779. skyboxTexture: this._skyboxTextureCDNUrl,
  89780. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  89781. backgroundYRotation: 0,
  89782. sizeAuto: true,
  89783. rootPosition: BABYLON.Vector3.Zero(),
  89784. setupImageProcessing: true,
  89785. environmentTexture: this._environmentTextureCDNUrl,
  89786. cameraExposure: 0.8,
  89787. cameraContrast: 1.2,
  89788. toneMappingEnabled: true,
  89789. };
  89790. };
  89791. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  89792. /**
  89793. * Gets the root mesh created by the helper.
  89794. */
  89795. get: function () {
  89796. return this._rootMesh;
  89797. },
  89798. enumerable: true,
  89799. configurable: true
  89800. });
  89801. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  89802. /**
  89803. * Gets the skybox created by the helper.
  89804. */
  89805. get: function () {
  89806. return this._skybox;
  89807. },
  89808. enumerable: true,
  89809. configurable: true
  89810. });
  89811. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  89812. /**
  89813. * Gets the skybox texture created by the helper.
  89814. */
  89815. get: function () {
  89816. return this._skyboxTexture;
  89817. },
  89818. enumerable: true,
  89819. configurable: true
  89820. });
  89821. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  89822. /**
  89823. * Gets the skybox material created by the helper.
  89824. */
  89825. get: function () {
  89826. return this._skyboxMaterial;
  89827. },
  89828. enumerable: true,
  89829. configurable: true
  89830. });
  89831. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  89832. /**
  89833. * Gets the ground mesh created by the helper.
  89834. */
  89835. get: function () {
  89836. return this._ground;
  89837. },
  89838. enumerable: true,
  89839. configurable: true
  89840. });
  89841. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  89842. /**
  89843. * Gets the ground texture created by the helper.
  89844. */
  89845. get: function () {
  89846. return this._groundTexture;
  89847. },
  89848. enumerable: true,
  89849. configurable: true
  89850. });
  89851. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  89852. /**
  89853. * Gets the ground mirror created by the helper.
  89854. */
  89855. get: function () {
  89856. return this._groundMirror;
  89857. },
  89858. enumerable: true,
  89859. configurable: true
  89860. });
  89861. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  89862. /**
  89863. * Gets the ground mirror render list to helps pushing the meshes
  89864. * you wish in the ground reflection.
  89865. */
  89866. get: function () {
  89867. if (this._groundMirror) {
  89868. return this._groundMirror.renderList;
  89869. }
  89870. return null;
  89871. },
  89872. enumerable: true,
  89873. configurable: true
  89874. });
  89875. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  89876. /**
  89877. * Gets the ground material created by the helper.
  89878. */
  89879. get: function () {
  89880. return this._groundMaterial;
  89881. },
  89882. enumerable: true,
  89883. configurable: true
  89884. });
  89885. /**
  89886. * Updates the background according to the new options
  89887. * @param options
  89888. */
  89889. EnvironmentHelper.prototype.updateOptions = function (options) {
  89890. var newOptions = __assign({}, this._options, options);
  89891. if (this._ground && !newOptions.createGround) {
  89892. this._ground.dispose();
  89893. this._ground = null;
  89894. }
  89895. if (this._groundMaterial && !newOptions.createGround) {
  89896. this._groundMaterial.dispose();
  89897. this._groundMaterial = null;
  89898. }
  89899. if (this._groundTexture) {
  89900. if (this._options.groundTexture != newOptions.groundTexture) {
  89901. this._groundTexture.dispose();
  89902. this._groundTexture = null;
  89903. }
  89904. }
  89905. if (this._skybox && !newOptions.createSkybox) {
  89906. this._skybox.dispose();
  89907. this._skybox = null;
  89908. }
  89909. if (this._skyboxMaterial && !newOptions.createSkybox) {
  89910. this._skyboxMaterial.dispose();
  89911. this._skyboxMaterial = null;
  89912. }
  89913. if (this._skyboxTexture) {
  89914. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  89915. this._skyboxTexture.dispose();
  89916. this._skyboxTexture = null;
  89917. }
  89918. }
  89919. if (this._groundMirror && !newOptions.enableGroundMirror) {
  89920. this._groundMirror.dispose();
  89921. this._groundMirror = null;
  89922. }
  89923. if (this._scene.environmentTexture) {
  89924. if (this._options.environmentTexture != newOptions.environmentTexture) {
  89925. this._scene.environmentTexture.dispose();
  89926. }
  89927. }
  89928. this._options = newOptions;
  89929. this._setupBackground();
  89930. this._setupImageProcessing();
  89931. };
  89932. /**
  89933. * Sets the primary color of all the available elements.
  89934. * @param color
  89935. */
  89936. EnvironmentHelper.prototype.setMainColor = function (color) {
  89937. if (this.groundMaterial) {
  89938. this.groundMaterial.primaryColor = color;
  89939. }
  89940. if (this.skyboxMaterial) {
  89941. this.skyboxMaterial.primaryColor = color;
  89942. }
  89943. if (this.groundMirror) {
  89944. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  89945. }
  89946. };
  89947. /**
  89948. * Setup the image processing according to the specified options.
  89949. */
  89950. EnvironmentHelper.prototype._setupImageProcessing = function () {
  89951. if (this._options.setupImageProcessing) {
  89952. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  89953. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  89954. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  89955. this._setupEnvironmentTexture();
  89956. }
  89957. };
  89958. /**
  89959. * Setup the environment texture according to the specified options.
  89960. */
  89961. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  89962. if (this._scene.environmentTexture) {
  89963. return;
  89964. }
  89965. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  89966. this._scene.environmentTexture = this._options.environmentTexture;
  89967. return;
  89968. }
  89969. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  89970. this._scene.environmentTexture = environmentTexture;
  89971. };
  89972. /**
  89973. * Setup the background according to the specified options.
  89974. */
  89975. EnvironmentHelper.prototype._setupBackground = function () {
  89976. if (!this._rootMesh) {
  89977. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  89978. }
  89979. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  89980. var sceneSize = this._getSceneSize();
  89981. if (this._options.createGround) {
  89982. this._setupGround(sceneSize);
  89983. this._setupGroundMaterial();
  89984. this._setupGroundDiffuseTexture();
  89985. if (this._options.enableGroundMirror) {
  89986. this._setupGroundMirrorTexture(sceneSize);
  89987. }
  89988. this._setupMirrorInGroundMaterial();
  89989. }
  89990. if (this._options.createSkybox) {
  89991. this._setupSkybox(sceneSize);
  89992. this._setupSkyboxMaterial();
  89993. this._setupSkyboxReflectionTexture();
  89994. }
  89995. this._rootMesh.position.x = sceneSize.rootPosition.x;
  89996. this._rootMesh.position.z = sceneSize.rootPosition.z;
  89997. this._rootMesh.position.y = sceneSize.rootPosition.y;
  89998. };
  89999. /**
  90000. * Get the scene sizes according to the setup.
  90001. */
  90002. EnvironmentHelper.prototype._getSceneSize = function () {
  90003. var _this = this;
  90004. var groundSize = this._options.groundSize;
  90005. var skyboxSize = this._options.skyboxSize;
  90006. var rootPosition = this._options.rootPosition;
  90007. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  90008. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  90009. }
  90010. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  90011. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  90012. });
  90013. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  90014. if (this._options.sizeAuto) {
  90015. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  90016. this._scene.activeCamera.upperRadiusLimit) {
  90017. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  90018. skyboxSize = groundSize;
  90019. }
  90020. var sceneDiagonalLenght = sceneDiagonal.length();
  90021. if (sceneDiagonalLenght > groundSize) {
  90022. groundSize = sceneDiagonalLenght * 2;
  90023. skyboxSize = groundSize;
  90024. }
  90025. // 10 % bigger.
  90026. groundSize *= 1.1;
  90027. skyboxSize *= 1.5;
  90028. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  90029. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  90030. }
  90031. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  90032. };
  90033. /**
  90034. * Setup the ground according to the specified options.
  90035. */
  90036. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  90037. var _this = this;
  90038. if (!this._ground) {
  90039. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  90040. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  90041. this._ground.parent = this._rootMesh;
  90042. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  90043. }
  90044. this._ground.receiveShadows = this._options.enableGroundShadow;
  90045. };
  90046. /**
  90047. * Setup the ground material according to the specified options.
  90048. */
  90049. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  90050. if (!this._groundMaterial) {
  90051. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  90052. }
  90053. this._groundMaterial.alpha = this._options.groundOpacity;
  90054. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  90055. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  90056. this._groundMaterial.primaryLevel = 1;
  90057. this._groundMaterial.primaryColor = this._options.groundColor;
  90058. this._groundMaterial.secondaryLevel = 0;
  90059. this._groundMaterial.tertiaryLevel = 0;
  90060. this._groundMaterial.useRGBColor = false;
  90061. this._groundMaterial.enableNoise = true;
  90062. if (this._ground) {
  90063. this._ground.material = this._groundMaterial;
  90064. }
  90065. };
  90066. /**
  90067. * Setup the ground diffuse texture according to the specified options.
  90068. */
  90069. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  90070. if (!this._groundMaterial) {
  90071. return;
  90072. }
  90073. if (this._groundTexture) {
  90074. return;
  90075. }
  90076. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  90077. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  90078. return;
  90079. }
  90080. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  90081. diffuseTexture.gammaSpace = false;
  90082. diffuseTexture.hasAlpha = true;
  90083. this._groundMaterial.diffuseTexture = diffuseTexture;
  90084. };
  90085. /**
  90086. * Setup the ground mirror texture according to the specified options.
  90087. */
  90088. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  90089. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90090. if (!this._groundMirror) {
  90091. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  90092. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  90093. this._groundMirror.anisotropicFilteringLevel = 1;
  90094. this._groundMirror.wrapU = wrapping;
  90095. this._groundMirror.wrapV = wrapping;
  90096. this._groundMirror.gammaSpace = false;
  90097. if (this._groundMirror.renderList) {
  90098. for (var i = 0; i < this._scene.meshes.length; i++) {
  90099. var mesh = this._scene.meshes[i];
  90100. if (mesh !== this._ground &&
  90101. mesh !== this._skybox &&
  90102. mesh !== this._rootMesh) {
  90103. this._groundMirror.renderList.push(mesh);
  90104. }
  90105. }
  90106. }
  90107. }
  90108. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  90109. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  90110. };
  90111. /**
  90112. * Setup the ground to receive the mirror texture.
  90113. */
  90114. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  90115. if (this._groundMaterial) {
  90116. this._groundMaterial.reflectionTexture = this._groundMirror;
  90117. this._groundMaterial.reflectionFresnel = true;
  90118. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  90119. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  90120. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  90121. }
  90122. };
  90123. /**
  90124. * Setup the skybox according to the specified options.
  90125. */
  90126. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  90127. var _this = this;
  90128. if (!this._skybox) {
  90129. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  90130. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  90131. }
  90132. this._skybox.parent = this._rootMesh;
  90133. };
  90134. /**
  90135. * Setup the skybox material according to the specified options.
  90136. */
  90137. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  90138. if (!this._skybox) {
  90139. return;
  90140. }
  90141. if (!this._skyboxMaterial) {
  90142. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  90143. }
  90144. this._skyboxMaterial.useRGBColor = false;
  90145. this._skyboxMaterial.primaryLevel = 1;
  90146. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  90147. this._skyboxMaterial.secondaryLevel = 0;
  90148. this._skyboxMaterial.tertiaryLevel = 0;
  90149. this._skyboxMaterial.enableNoise = true;
  90150. this._skybox.material = this._skyboxMaterial;
  90151. };
  90152. /**
  90153. * Setup the skybox reflection texture according to the specified options.
  90154. */
  90155. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  90156. if (!this._skyboxMaterial) {
  90157. return;
  90158. }
  90159. if (this._skyboxTexture) {
  90160. return;
  90161. }
  90162. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  90163. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  90164. return;
  90165. }
  90166. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  90167. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  90168. this._skyboxTexture.gammaSpace = false;
  90169. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  90170. };
  90171. /**
  90172. * Dispose all the elements created by the Helper.
  90173. */
  90174. EnvironmentHelper.prototype.dispose = function () {
  90175. if (this._groundMaterial) {
  90176. this._groundMaterial.dispose(true, true);
  90177. }
  90178. if (this._skyboxMaterial) {
  90179. this._skyboxMaterial.dispose(true, true);
  90180. }
  90181. this._rootMesh.dispose(false);
  90182. };
  90183. /**
  90184. * Default ground texture URL.
  90185. */
  90186. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  90187. /**
  90188. * Default skybox texture URL.
  90189. */
  90190. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  90191. /**
  90192. * Default environment texture URL.
  90193. */
  90194. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  90195. return EnvironmentHelper;
  90196. }());
  90197. BABYLON.EnvironmentHelper = EnvironmentHelper;
  90198. })(BABYLON || (BABYLON = {}));
  90199. //# sourceMappingURL=babylon.environmentHelper.js.map
  90200. var BABYLON;
  90201. (function (BABYLON) {
  90202. /**
  90203. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  90204. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  90205. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  90206. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  90207. */
  90208. var VideoDome = /** @class */ (function (_super) {
  90209. __extends(VideoDome, _super);
  90210. /**
  90211. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  90212. * @param name Element's name, child elements will append suffixes for their own names.
  90213. * @param urlsOrVideo
  90214. * @param options An object containing optional or exposed sub element properties:
  90215. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  90216. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  90217. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  90218. * @param options **loop=true** Automatically loop video on end.
  90219. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  90220. */
  90221. function VideoDome(name, urlsOrVideo, options, scene) {
  90222. var _this = _super.call(this, name, scene) || this;
  90223. // set defaults and manage values
  90224. name = name || "videoDome";
  90225. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  90226. options.clickToPlay = Boolean(options.clickToPlay);
  90227. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  90228. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  90229. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  90230. // create
  90231. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  90232. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  90233. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  90234. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  90235. flat: false,
  90236. radius: options.size,
  90237. subdivisions: options.resolution,
  90238. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  90239. }, scene);
  90240. // configure material
  90241. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  90242. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  90243. material.reflectionTexture = _this._videoTexture;
  90244. material.useEquirectangularFOV = true;
  90245. material.fovMultiplier = 1.0;
  90246. // configure mesh
  90247. _this._mesh.material = material;
  90248. _this._mesh.parent = _this;
  90249. // optional configuration
  90250. if (options.clickToPlay) {
  90251. scene.onPointerUp = function () {
  90252. _this._videoTexture.video.play();
  90253. };
  90254. }
  90255. return _this;
  90256. }
  90257. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  90258. /**
  90259. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  90260. * Also see the options.resolution property.
  90261. */
  90262. get: function () {
  90263. return this._material.fovMultiplier;
  90264. },
  90265. set: function (value) {
  90266. this._material.fovMultiplier = value;
  90267. },
  90268. enumerable: true,
  90269. configurable: true
  90270. });
  90271. /**
  90272. * Releases all associated resources
  90273. */
  90274. VideoDome.prototype.dispose = function () {
  90275. _super.prototype.dispose.call(this);
  90276. this._videoTexture.dispose();
  90277. this._mesh.dispose();
  90278. this._material.dispose();
  90279. };
  90280. return VideoDome;
  90281. }(BABYLON.Node));
  90282. BABYLON.VideoDome = VideoDome;
  90283. })(BABYLON || (BABYLON = {}));
  90284. //# sourceMappingURL=babylon.videoDome.js.map
  90285. 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"};
  90286. 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};"};
  90287. (function universalModuleDefinition(root, factory) {
  90288. var f = factory();
  90289. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  90290. globalObject["BABYLON"] = f;
  90291. if(true)
  90292. module.exports = f;
  90293. else if(typeof define === 'function' && define.amd)
  90294. define("BABYLON", factory);
  90295. else if(typeof exports === 'object')
  90296. exports["BABYLON"] = f;
  90297. else {
  90298. root["BABYLON"] = f;
  90299. }
  90300. })(this, function() {
  90301. return BABYLON;
  90302. });
  90303. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2)))
  90304. /***/ }),
  90305. /* 1 */
  90306. /***/ (function(module, exports, __webpack_require__) {
  90307. "use strict";
  90308. Object.defineProperty(exports, "__esModule", { value: true });
  90309. var babylonjs_1 = __webpack_require__(0);
  90310. var helper_1 = __webpack_require__(3);
  90311. var HTMLMapper = (function () {
  90312. function HTMLMapper() {
  90313. }
  90314. HTMLMapper.prototype.map = function (element) {
  90315. var config = {};
  90316. var _loop_1 = function (attrIdx) {
  90317. var attr = element.attributes.item(attrIdx);
  90318. var split = attr.nodeName.split('.');
  90319. split.reduce(function (currentConfig, key, idx) {
  90320. var camelKey = helper_1.kebabToCamel(key);
  90321. if (idx === split.length - 1) {
  90322. var val = attr.nodeValue;
  90323. if (val === "true") {
  90324. val = true;
  90325. }
  90326. else if (val === "false") {
  90327. val = false;
  90328. }
  90329. else {
  90330. var number = parseFloat(val);
  90331. if (!isNaN(number)) {
  90332. val = number;
  90333. }
  90334. }
  90335. currentConfig[camelKey] = val;
  90336. }
  90337. else {
  90338. currentConfig[camelKey] = currentConfig[camelKey] || {};
  90339. }
  90340. return currentConfig[camelKey];
  90341. }, config);
  90342. };
  90343. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  90344. _loop_1(attrIdx);
  90345. }
  90346. return config;
  90347. };
  90348. return HTMLMapper;
  90349. }());
  90350. var JSONMapper = (function () {
  90351. function JSONMapper() {
  90352. }
  90353. JSONMapper.prototype.map = function (rawSource) {
  90354. return JSON.parse(rawSource);
  90355. };
  90356. return JSONMapper;
  90357. }());
  90358. var DOMMapper = (function () {
  90359. function DOMMapper() {
  90360. }
  90361. DOMMapper.prototype.map = function (baseElement) {
  90362. var htmlMapper = new HTMLMapper();
  90363. var config = htmlMapper.map(baseElement);
  90364. var traverseChildren = function (element, partConfig) {
  90365. var children = element.children;
  90366. if (children.length) {
  90367. for (var i = 0; i < children.length; ++i) {
  90368. var item = children.item(i);
  90369. var configMapped = htmlMapper.map(item);
  90370. var key = helper_1.kebabToCamel(item.nodeName.toLowerCase());
  90371. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  90372. partConfig[key] = [];
  90373. }
  90374. else {
  90375. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  90376. partConfig.push(configMapped);
  90377. }
  90378. else if (partConfig[key]) {
  90379. element.setAttribute('array', 'true');
  90380. var oldItem = partConfig[key];
  90381. partConfig = [oldItem, configMapped];
  90382. }
  90383. else {
  90384. partConfig[key] = configMapped;
  90385. }
  90386. }
  90387. traverseChildren(item, partConfig[key] || configMapped);
  90388. }
  90389. }
  90390. return partConfig;
  90391. };
  90392. traverseChildren(baseElement, config);
  90393. return config;
  90394. };
  90395. return DOMMapper;
  90396. }());
  90397. var MapperManager = (function () {
  90398. function MapperManager() {
  90399. this.mappers = {
  90400. "html": new HTMLMapper(),
  90401. "json": new JSONMapper(),
  90402. "dom": new DOMMapper()
  90403. };
  90404. }
  90405. MapperManager.prototype.getMapper = function (type) {
  90406. if (!this.mappers[type]) {
  90407. babylonjs_1.Tools.Error("No mapper defined for " + type);
  90408. }
  90409. return this.mappers[type] || this.mappers[MapperManager.DefaultMapper];
  90410. };
  90411. MapperManager.prototype.registerMapper = function (type, mapper) {
  90412. this.mappers[type] = mapper;
  90413. };
  90414. MapperManager.DefaultMapper = 'json';
  90415. return MapperManager;
  90416. }());
  90417. exports.MapperManager = MapperManager;
  90418. exports.mapperManager = new MapperManager();
  90419. /***/ }),
  90420. /* 2 */
  90421. /***/ (function(module, exports) {
  90422. var g;
  90423. // This works in non-strict mode
  90424. g = (function() {
  90425. return this;
  90426. })();
  90427. try {
  90428. // This works if eval is allowed (see CSP)
  90429. g = g || Function("return this")() || (1,eval)("this");
  90430. } catch(e) {
  90431. // This works if the window reference is available
  90432. if(typeof window === "object")
  90433. g = window;
  90434. }
  90435. // g can still be undefined, but nothing to do about it...
  90436. // We return undefined, instead of nothing here, so it's
  90437. // easier to handle this case. if(!global) { ...}
  90438. module.exports = g;
  90439. /***/ }),
  90440. /* 3 */
  90441. /***/ (function(module, exports, __webpack_require__) {
  90442. "use strict";
  90443. Object.defineProperty(exports, "__esModule", { value: true });
  90444. function isUrl(urlToCheck) {
  90445. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  90446. return true;
  90447. }
  90448. return false;
  90449. }
  90450. exports.isUrl = isUrl;
  90451. function kebabToCamel(s) {
  90452. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  90453. }
  90454. exports.kebabToCamel = kebabToCamel;
  90455. function camelToKebab(str) {
  90456. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  90457. }
  90458. exports.camelToKebab = camelToKebab;
  90459. /***/ }),
  90460. /* 4 */
  90461. /***/ (function(module, exports, __webpack_require__) {
  90462. "use strict";
  90463. Object.defineProperty(exports, "__esModule", { value: true });
  90464. var babylonjs_1 = __webpack_require__(0);
  90465. var ViewerManager = (function () {
  90466. function ViewerManager() {
  90467. this.viewers = {};
  90468. this.onViewerAddedObservable = new babylonjs_1.Observable();
  90469. }
  90470. ViewerManager.prototype.addViewer = function (viewer) {
  90471. this.viewers[viewer.getBaseId()] = viewer;
  90472. this._onViewerAdded(viewer);
  90473. };
  90474. ViewerManager.prototype.getViewerById = function (id) {
  90475. return this.viewers[id];
  90476. };
  90477. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  90478. for (var id in this.viewers) {
  90479. if (this.viewers[id].containerElement === element) {
  90480. return this.getViewerById(id);
  90481. }
  90482. }
  90483. };
  90484. ViewerManager.prototype.getViewerPromiseById = function (id) {
  90485. var _this = this;
  90486. return new Promise(function (resolve, reject) {
  90487. var localViewer = _this.getViewerById(id);
  90488. if (localViewer) {
  90489. return resolve(localViewer);
  90490. }
  90491. var viewerFunction = function (viewer) {
  90492. if (viewer.getBaseId() === id) {
  90493. resolve(viewer);
  90494. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  90495. }
  90496. };
  90497. _this.onViewerAddedObservable.add(viewerFunction);
  90498. });
  90499. };
  90500. ViewerManager.prototype._onViewerAdded = function (viewer) {
  90501. this.onViewerAdded && this.onViewerAdded(viewer);
  90502. this.onViewerAddedObservable.notifyObservers(viewer);
  90503. };
  90504. return ViewerManager;
  90505. }());
  90506. exports.ViewerManager = ViewerManager;
  90507. exports.viewerManager = new ViewerManager();
  90508. /***/ }),
  90509. /* 5 */
  90510. /***/ (function(module, exports, __webpack_require__) {
  90511. "use strict";
  90512. var __extends = (this && this.__extends) || (function () {
  90513. var extendStatics = Object.setPrototypeOf ||
  90514. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  90515. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  90516. return function (d, b) {
  90517. extendStatics(d, b);
  90518. function __() { this.constructor = d; }
  90519. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  90520. };
  90521. })();
  90522. Object.defineProperty(exports, "__esModule", { value: true });
  90523. var viewer_1 = __webpack_require__(6);
  90524. var babylonjs_1 = __webpack_require__(0);
  90525. var DefaultViewer = (function (_super) {
  90526. __extends(DefaultViewer, _super);
  90527. function DefaultViewer(containerElement, initialConfiguration) {
  90528. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  90529. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  90530. _this.containerElement = containerElement;
  90531. _this.onModelLoaded = function (meshes) {
  90532. var hideLoadingDelay = 500;
  90533. if (_this.configuration.lab && _this.configuration.lab.hideLoadingDelay !== undefined) {
  90534. hideLoadingDelay = _this.configuration.lab.hideLoadingDelay;
  90535. }
  90536. setTimeout(function () {
  90537. _this.hideLoadingScreen();
  90538. }, hideLoadingDelay);
  90539. meshes[0].rotation.y += Math.PI;
  90540. return;
  90541. };
  90542. _this.onModelLoadedObservable.add(_this.onModelLoaded);
  90543. return _this;
  90544. }
  90545. DefaultViewer.prototype.initScene = function () {
  90546. var _this = this;
  90547. return _super.prototype.initScene.call(this).then(function () {
  90548. _this.extendClassWithConfig(_this.scene, _this.configuration.scene);
  90549. return _this.scene;
  90550. });
  90551. };
  90552. DefaultViewer.prototype.onTemplatesLoaded = function () {
  90553. var _this = this;
  90554. this.showLoadingScreen();
  90555. this.initNavbar();
  90556. var closeButton = document.getElementById('close-button');
  90557. if (closeButton) {
  90558. closeButton.addEventListener('pointerdown', function () {
  90559. _this.hideOverlayScreen();
  90560. });
  90561. }
  90562. return _super.prototype.onTemplatesLoaded.call(this);
  90563. };
  90564. DefaultViewer.prototype.initNavbar = function () {
  90565. var navbar = this.templateManager.getTemplate('navBar');
  90566. if (navbar) {
  90567. var navbarHeight_1 = navbar.parent.clientHeight + 'px';
  90568. var navbarShown_1 = true;
  90569. var timeoutCancel_1;
  90570. var triggerNavbar = function (show, evt) {
  90571. if (show === void 0) { show = false; }
  90572. if (!navbar || evt.button > 0)
  90573. return;
  90574. timeoutCancel_1 && clearTimeout(timeoutCancel_1);
  90575. if (show === navbarShown_1)
  90576. return;
  90577. if (show) {
  90578. navbar.parent.style.bottom = show ? '0px' : '-' + navbarHeight_1;
  90579. navbarShown_1 = show;
  90580. }
  90581. else {
  90582. var visibilityTimeout = 2000;
  90583. if (navbar.configuration.params && navbar.configuration.params.visibilityTimeout !== undefined) {
  90584. visibilityTimeout = navbar.configuration.params.visibilityTimeout;
  90585. }
  90586. timeoutCancel_1 = setTimeout(function () {
  90587. if (navbar) {
  90588. navbar.parent.style.bottom = '-' + navbarHeight_1;
  90589. }
  90590. navbarShown_1 = show;
  90591. }, visibilityTimeout);
  90592. }
  90593. };
  90594. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerout');
  90595. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, true), 'pointerdown');
  90596. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerup');
  90597. this.templateManager.eventManager.registerCallback('navBar', triggerNavbar.bind(this, true), 'pointerover');
  90598. var viewerTemplate = this.templateManager.getTemplate('viewer');
  90599. var viewerElement_1 = viewerTemplate && viewerTemplate.parent;
  90600. var triggerFullscren = function (eventData) {
  90601. if (viewerElement_1) {
  90602. var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  90603. if (!fullscreenElement) {
  90604. var requestFullScreen = viewerElement_1.requestFullscreen || viewerElement_1.webkitRequestFullscreen || viewerElement_1.msRequestFullscreen || viewerElement_1.mozRequestFullScreen;
  90605. requestFullScreen.call(viewerElement_1);
  90606. }
  90607. else {
  90608. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen;
  90609. exitFullscreen.call(document);
  90610. }
  90611. }
  90612. };
  90613. this.templateManager.eventManager.registerCallback('navBar', triggerFullscren, 'pointerdown', '#fullscreen-button');
  90614. }
  90615. };
  90616. DefaultViewer.prototype.prepareContainerElement = function () {
  90617. this.containerElement.style.position = 'relative';
  90618. this.containerElement.style.display = 'flex';
  90619. };
  90620. DefaultViewer.prototype.configureModel = function (modelConfiguration, focusMeshes) {
  90621. if (focusMeshes === void 0) { focusMeshes = this.scene.meshes; }
  90622. _super.prototype.configureModel.call(this, modelConfiguration, focusMeshes);
  90623. var navbar = this.templateManager.getTemplate('navBar');
  90624. if (!navbar)
  90625. return;
  90626. var metadataContainer = navbar.parent.querySelector('#model-metadata');
  90627. if (metadataContainer) {
  90628. if (modelConfiguration.title !== undefined) {
  90629. var element = metadataContainer.querySelector('span.model-title');
  90630. if (element) {
  90631. element.innerHTML = modelConfiguration.title;
  90632. }
  90633. }
  90634. if (modelConfiguration.subtitle !== undefined) {
  90635. var element = metadataContainer.querySelector('span.model-subtitle');
  90636. if (element) {
  90637. element.innerHTML = modelConfiguration.subtitle;
  90638. }
  90639. }
  90640. if (modelConfiguration.thumbnail !== undefined) {
  90641. metadataContainer.querySelector('.thumbnail').style.backgroundImage = "url('" + modelConfiguration.thumbnail + "')";
  90642. }
  90643. }
  90644. };
  90645. DefaultViewer.prototype.loadModel = function (model) {
  90646. var _this = this;
  90647. if (model === void 0) { model = this.configuration.model; }
  90648. this.showLoadingScreen();
  90649. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  90650. console.log(error);
  90651. _this.hideLoadingScreen();
  90652. _this.showOverlayScreen('error');
  90653. return _this.scene;
  90654. });
  90655. };
  90656. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  90657. var _this = this;
  90658. var template = this.templateManager.getTemplate('overlay');
  90659. if (!template)
  90660. return Promise.resolve('Overlay template not found');
  90661. return template.show((function (template) {
  90662. var canvasRect = _this.containerElement.getBoundingClientRect();
  90663. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  90664. template.parent.style.display = 'flex';
  90665. template.parent.style.width = canvasRect.width + "px";
  90666. template.parent.style.height = canvasRect.height + "px";
  90667. template.parent.style.opacity = "1";
  90668. var subTemplate = _this.templateManager.getTemplate(subScreen);
  90669. if (!subTemplate) {
  90670. return Promise.reject(subScreen + ' template not found');
  90671. }
  90672. return subTemplate.show((function (template) {
  90673. template.parent.style.display = 'flex';
  90674. return Promise.resolve(template);
  90675. }));
  90676. }));
  90677. };
  90678. DefaultViewer.prototype.hideOverlayScreen = function () {
  90679. var template = this.templateManager.getTemplate('overlay');
  90680. if (!template)
  90681. return Promise.resolve('Overlay template not found');
  90682. return template.hide((function (template) {
  90683. template.parent.style.opacity = "0";
  90684. var onTransitionEnd = function () {
  90685. template.parent.removeEventListener("transitionend", onTransitionEnd);
  90686. template.parent.style.display = 'none';
  90687. };
  90688. template.parent.addEventListener("transitionend", onTransitionEnd);
  90689. var overlays = template.parent.querySelectorAll('.overlay');
  90690. if (overlays) {
  90691. for (var i = 0; i < overlays.length; ++i) {
  90692. var htmlElement = overlays.item(i);
  90693. htmlElement.style.display = 'none';
  90694. }
  90695. }
  90696. return Promise.resolve(template);
  90697. }));
  90698. };
  90699. DefaultViewer.prototype.showLoadingScreen = function () {
  90700. var _this = this;
  90701. var template = this.templateManager.getTemplate('loadingScreen');
  90702. if (!template)
  90703. return Promise.resolve('Loading Screen template not found');
  90704. return template.show((function (template) {
  90705. var canvasRect = _this.containerElement.getBoundingClientRect();
  90706. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  90707. template.parent.style.display = 'flex';
  90708. template.parent.style.width = canvasRect.width + "px";
  90709. template.parent.style.height = canvasRect.height + "px";
  90710. template.parent.style.opacity = "1";
  90711. template.parent.style.backgroundColor = "black";
  90712. return Promise.resolve(template);
  90713. }));
  90714. };
  90715. DefaultViewer.prototype.hideLoadingScreen = function () {
  90716. var template = this.templateManager.getTemplate('loadingScreen');
  90717. if (!template)
  90718. return Promise.resolve('Loading Screen template not found');
  90719. return template.hide((function (template) {
  90720. template.parent.style.opacity = "0";
  90721. var onTransitionEnd = function () {
  90722. template.parent.removeEventListener("transitionend", onTransitionEnd);
  90723. template.parent.style.display = 'none';
  90724. };
  90725. template.parent.addEventListener("transitionend", onTransitionEnd);
  90726. return Promise.resolve(template);
  90727. }));
  90728. };
  90729. DefaultViewer.prototype.configureLights = function (lightsConfiguration, focusMeshes) {
  90730. var _this = this;
  90731. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  90732. if (focusMeshes === void 0) { focusMeshes = this.scene.meshes; }
  90733. _super.prototype.configureLights.call(this, lightsConfiguration, focusMeshes);
  90734. if (this.configuration.lab && this.configuration.lab.flashlight) {
  90735. var pointerPosition = BABYLON.Vector3.Zero();
  90736. var lightTarget_1;
  90737. var angle = 0.5;
  90738. var exponent = Math.PI / 2;
  90739. if (typeof this.configuration.lab.flashlight === "object") {
  90740. exponent = this.configuration.lab.flashlight.exponent || exponent;
  90741. angle = this.configuration.lab.flashlight.angle || angle;
  90742. }
  90743. var flashlight = new babylonjs_1.SpotLight("flashlight", babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), exponent, angle, this.scene);
  90744. if (typeof this.configuration.lab.flashlight === "object") {
  90745. flashlight.intensity = this.configuration.lab.flashlight.intensity || flashlight.intensity;
  90746. if (this.configuration.lab.flashlight.diffuse) {
  90747. flashlight.diffuse.r = this.configuration.lab.flashlight.diffuse.r;
  90748. flashlight.diffuse.g = this.configuration.lab.flashlight.diffuse.g;
  90749. flashlight.diffuse.b = this.configuration.lab.flashlight.diffuse.b;
  90750. }
  90751. if (this.configuration.lab.flashlight.specular) {
  90752. flashlight.specular.r = this.configuration.lab.flashlight.specular.r;
  90753. flashlight.specular.g = this.configuration.lab.flashlight.specular.g;
  90754. flashlight.specular.b = this.configuration.lab.flashlight.specular.b;
  90755. }
  90756. }
  90757. this.scene.constantlyUpdateMeshUnderPointer = true;
  90758. this.scene.onPointerObservable.add(function (eventData, eventState) {
  90759. if (eventData.type === 4 && eventData.pickInfo) {
  90760. lightTarget_1 = (eventData.pickInfo.pickedPoint);
  90761. }
  90762. else {
  90763. lightTarget_1 = undefined;
  90764. }
  90765. });
  90766. var updateFlashlightFunction = function () {
  90767. if (_this.camera && flashlight) {
  90768. flashlight.position.copyFrom(_this.camera.position);
  90769. if (lightTarget_1) {
  90770. lightTarget_1.subtractToRef(flashlight.position, flashlight.direction);
  90771. }
  90772. }
  90773. };
  90774. this.scene.registerBeforeRender(updateFlashlightFunction);
  90775. this.registeredOnBeforerenderFunctions.push(updateFlashlightFunction);
  90776. }
  90777. };
  90778. return DefaultViewer;
  90779. }(viewer_1.AbstractViewer));
  90780. exports.DefaultViewer = DefaultViewer;
  90781. /***/ }),
  90782. /* 6 */
  90783. /***/ (function(module, exports, __webpack_require__) {
  90784. "use strict";
  90785. Object.defineProperty(exports, "__esModule", { value: true });
  90786. var viewerManager_1 = __webpack_require__(4);
  90787. var templateManager_1 = __webpack_require__(19);
  90788. var loader_1 = __webpack_require__(22);
  90789. var babylonjs_1 = __webpack_require__(0);
  90790. var deepmerge = __webpack_require__(14);
  90791. var AbstractViewer = (function () {
  90792. function AbstractViewer(containerElement, initialConfiguration) {
  90793. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  90794. var _this = this;
  90795. this.containerElement = containerElement;
  90796. this.resize = function () {
  90797. if (!_this.isCanvasInDOM()) {
  90798. return;
  90799. }
  90800. if (_this.canvas.clientWidth <= 0 || _this.canvas.clientHeight <= 0) {
  90801. return;
  90802. }
  90803. _this.engine.resize();
  90804. };
  90805. this.render = function () {
  90806. _this.scene && _this.scene.activeCamera && _this.scene.render();
  90807. };
  90808. if (containerElement.id) {
  90809. this.baseId = containerElement.id;
  90810. }
  90811. else {
  90812. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  90813. }
  90814. this.onSceneInitObservable = new babylonjs_1.Observable();
  90815. this.onEngineInitObservable = new babylonjs_1.Observable();
  90816. this.onModelLoadedObservable = new babylonjs_1.Observable();
  90817. this.onModelLoadProgressObservable = new babylonjs_1.Observable();
  90818. this.onModelLoadErrorObservable = new babylonjs_1.Observable();
  90819. this.onInitDoneObservable = new babylonjs_1.Observable();
  90820. this.onLoaderInitObservable = new babylonjs_1.Observable();
  90821. this.registeredOnBeforerenderFunctions = [];
  90822. viewerManager_1.viewerManager.addViewer(this);
  90823. this.templateManager = new templateManager_1.TemplateManager(containerElement);
  90824. this.prepareContainerElement();
  90825. loader_1.default.loadConfiguration(initialConfiguration, function (configuration) {
  90826. _this.configuration = deepmerge(_this.configuration || {}, configuration);
  90827. if (_this.configuration.observers) {
  90828. _this.configureObservers(_this.configuration.observers);
  90829. }
  90830. var templateConfiguration = _this.configuration.templates || {};
  90831. _this.templateManager.initTemplate(templateConfiguration);
  90832. _this.templateManager.onAllLoaded.add(function () {
  90833. var canvas = _this.templateManager.getCanvas();
  90834. if (canvas) {
  90835. _this.canvas = canvas;
  90836. }
  90837. _this._onTemplateLoaded();
  90838. });
  90839. });
  90840. }
  90841. Object.defineProperty(AbstractViewer.prototype, "isHdrSupported", {
  90842. get: function () {
  90843. return this._hdrSupport;
  90844. },
  90845. enumerable: true,
  90846. configurable: true
  90847. });
  90848. AbstractViewer.prototype.getBaseId = function () {
  90849. return this.baseId;
  90850. };
  90851. AbstractViewer.prototype.isCanvasInDOM = function () {
  90852. return !!this.canvas && !!this.canvas.parentElement;
  90853. };
  90854. AbstractViewer.prototype.updateConfiguration = function (newConfiguration) {
  90855. if (newConfiguration === void 0) { newConfiguration = this.configuration; }
  90856. this.configuration = deepmerge(this.configuration || {}, newConfiguration);
  90857. if (newConfiguration.scene) {
  90858. this.configureScene(newConfiguration.scene);
  90859. }
  90860. if (newConfiguration.optimizer) {
  90861. this.configureOptimizer(newConfiguration.optimizer);
  90862. }
  90863. if (newConfiguration.observers) {
  90864. this.configureObservers(newConfiguration.observers);
  90865. }
  90866. if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  90867. this.configureModel(newConfiguration.model);
  90868. }
  90869. if (newConfiguration.lights) {
  90870. this.configureLights(newConfiguration.lights);
  90871. }
  90872. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  90873. this.configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  90874. }
  90875. if (newConfiguration.camera) {
  90876. this.configureCamera(newConfiguration.camera);
  90877. }
  90878. };
  90879. AbstractViewer.prototype.configureEnvironment = function (skyboxConifguration, groundConfiguration) {
  90880. if (!skyboxConifguration && !groundConfiguration) {
  90881. if (this.environmentHelper) {
  90882. this.environmentHelper.dispose();
  90883. delete this.environmentHelper;
  90884. }
  90885. ;
  90886. return Promise.resolve(this.scene);
  90887. }
  90888. var options = {
  90889. createGround: !!groundConfiguration,
  90890. createSkybox: !!skyboxConifguration,
  90891. setupImageProcessing: false
  90892. };
  90893. if (groundConfiguration) {
  90894. var groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  90895. var groundSize = groundConfig.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  90896. if (groundSize) {
  90897. options.groundSize = groundSize;
  90898. }
  90899. options.enableGroundShadow = groundConfig === true || groundConfig.receiveShadows;
  90900. if (groundConfig.shadowLevel !== undefined) {
  90901. options.groundShadowLevel = groundConfig.shadowLevel;
  90902. }
  90903. options.enableGroundMirror = !!groundConfig.mirror;
  90904. if (groundConfig.texture) {
  90905. options.groundTexture = groundConfig.texture;
  90906. }
  90907. if (groundConfig.color) {
  90908. options.groundColor = new babylonjs_1.Color3(groundConfig.color.r, groundConfig.color.g, groundConfig.color.b);
  90909. }
  90910. if (groundConfig.opacity !== undefined) {
  90911. options.groundOpacity = groundConfig.opacity;
  90912. }
  90913. if (groundConfig.mirror) {
  90914. options.enableGroundMirror = true;
  90915. if (typeof groundConfig.mirror === "object") {
  90916. if (groundConfig.mirror.amount !== undefined)
  90917. options.groundMirrorAmount = groundConfig.mirror.amount;
  90918. if (groundConfig.mirror.sizeRatio !== undefined)
  90919. options.groundMirrorSizeRatio = groundConfig.mirror.sizeRatio;
  90920. if (groundConfig.mirror.blurKernel !== undefined)
  90921. options.groundMirrorBlurKernel = groundConfig.mirror.blurKernel;
  90922. if (groundConfig.mirror.fresnelWeight !== undefined)
  90923. options.groundMirrorFresnelWeight = groundConfig.mirror.fresnelWeight;
  90924. if (groundConfig.mirror.fallOffDistance !== undefined)
  90925. options.groundMirrorFallOffDistance = groundConfig.mirror.fallOffDistance;
  90926. if (this.defaultPipelineTextureType !== undefined)
  90927. options.groundMirrorTextureType = this.defaultPipelineTextureType;
  90928. }
  90929. }
  90930. }
  90931. var postInitSkyboxMaterial = false;
  90932. if (skyboxConifguration) {
  90933. var conf = skyboxConifguration === true ? {} : skyboxConifguration;
  90934. if (conf.material && conf.material.imageProcessingConfiguration) {
  90935. options.setupImageProcessing = false;
  90936. }
  90937. var skyboxSize = conf.scale;
  90938. if (skyboxSize) {
  90939. options.skyboxSize = skyboxSize;
  90940. }
  90941. options.sizeAuto = !options.skyboxSize;
  90942. if (conf.color) {
  90943. options.skyboxColor = new babylonjs_1.Color3(conf.color.r, conf.color.g, conf.color.b);
  90944. }
  90945. if (conf.cubeTexture && conf.cubeTexture.url) {
  90946. if (typeof conf.cubeTexture.url === "string") {
  90947. options.skyboxTexture = conf.cubeTexture.url;
  90948. }
  90949. else {
  90950. postInitSkyboxMaterial = true;
  90951. }
  90952. }
  90953. if (conf.material && conf.material.imageProcessingConfiguration) {
  90954. postInitSkyboxMaterial = true;
  90955. }
  90956. }
  90957. options.setupImageProcessing = false;
  90958. if (!this.environmentHelper) {
  90959. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  90960. }
  90961. else {
  90962. var scene = this.environmentHelper.rootMesh.getScene();
  90963. if (scene !== this.scene) {
  90964. this.environmentHelper.dispose();
  90965. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  90966. }
  90967. else {
  90968. this.environmentHelper.updateOptions(options);
  90969. }
  90970. }
  90971. if (postInitSkyboxMaterial) {
  90972. var skyboxMaterial = this.environmentHelper.skyboxMaterial;
  90973. if (skyboxMaterial) {
  90974. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material && skyboxConifguration.material.imageProcessingConfiguration) {
  90975. this.extendClassWithConfig(skyboxMaterial.imageProcessingConfiguration, skyboxConifguration.material.imageProcessingConfiguration);
  90976. }
  90977. }
  90978. }
  90979. };
  90980. AbstractViewer.prototype.configureScene = function (sceneConfig, optimizerConfig) {
  90981. if (!this.scene) {
  90982. return;
  90983. }
  90984. if (sceneConfig.debug) {
  90985. this.scene.debugLayer.show();
  90986. }
  90987. else {
  90988. if (this.scene.debugLayer.isVisible()) {
  90989. this.scene.debugLayer.hide();
  90990. }
  90991. }
  90992. if (sceneConfig.clearColor) {
  90993. var cc = sceneConfig.clearColor;
  90994. var oldcc = this.scene.clearColor;
  90995. if (cc.r !== undefined) {
  90996. oldcc.r = cc.r;
  90997. }
  90998. if (cc.g !== undefined) {
  90999. oldcc.g = cc.g;
  91000. }
  91001. if (cc.b !== undefined) {
  91002. oldcc.b = cc.b;
  91003. }
  91004. if (cc.a !== undefined) {
  91005. oldcc.a = cc.a;
  91006. }
  91007. }
  91008. if (sceneConfig.imageProcessingConfiguration) {
  91009. this.extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  91010. }
  91011. if (sceneConfig.environmentTexture) {
  91012. if (this.scene.environmentTexture) {
  91013. this.scene.environmentTexture.dispose();
  91014. }
  91015. var environmentTexture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  91016. this.scene.environmentTexture = environmentTexture;
  91017. }
  91018. if (sceneConfig.autoRotate) {
  91019. this.camera.useAutoRotationBehavior = true;
  91020. }
  91021. };
  91022. AbstractViewer.prototype.configureOptimizer = function (optimizerConfig) {
  91023. if (typeof optimizerConfig === 'boolean') {
  91024. if (this.sceneOptimizer) {
  91025. this.sceneOptimizer.stop();
  91026. this.sceneOptimizer.dispose();
  91027. delete this.sceneOptimizer;
  91028. }
  91029. if (optimizerConfig) {
  91030. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene);
  91031. this.sceneOptimizer.start();
  91032. }
  91033. }
  91034. else {
  91035. var optimizerOptions = new babylonjs_1.SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  91036. if (optimizerConfig.degradation) {
  91037. switch (optimizerConfig.degradation) {
  91038. case "low":
  91039. optimizerOptions = babylonjs_1.SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  91040. break;
  91041. case "moderate":
  91042. optimizerOptions = babylonjs_1.SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  91043. break;
  91044. case "hight":
  91045. optimizerOptions = babylonjs_1.SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  91046. break;
  91047. }
  91048. }
  91049. if (this.sceneOptimizer) {
  91050. this.sceneOptimizer.stop();
  91051. this.sceneOptimizer.dispose();
  91052. }
  91053. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  91054. this.sceneOptimizer.start();
  91055. }
  91056. };
  91057. AbstractViewer.prototype.configureObservers = function (observersConfiguration) {
  91058. if (observersConfiguration.onEngineInit) {
  91059. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  91060. }
  91061. else {
  91062. if (observersConfiguration.onEngineInit === '' && this.configuration.observers && this.configuration.observers.onEngineInit) {
  91063. this.onEngineInitObservable.removeCallback(window[this.configuration.observers.onEngineInit]);
  91064. }
  91065. }
  91066. if (observersConfiguration.onSceneInit) {
  91067. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  91068. }
  91069. else {
  91070. if (observersConfiguration.onSceneInit === '' && this.configuration.observers && this.configuration.observers.onSceneInit) {
  91071. this.onSceneInitObservable.removeCallback(window[this.configuration.observers.onSceneInit]);
  91072. }
  91073. }
  91074. if (observersConfiguration.onModelLoaded) {
  91075. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  91076. }
  91077. else {
  91078. if (observersConfiguration.onModelLoaded === '' && this.configuration.observers && this.configuration.observers.onModelLoaded) {
  91079. this.onModelLoadedObservable.removeCallback(window[this.configuration.observers.onModelLoaded]);
  91080. }
  91081. }
  91082. };
  91083. AbstractViewer.prototype.configureCamera = function (cameraConfig, focusMeshes) {
  91084. var _this = this;
  91085. if (focusMeshes === void 0) { focusMeshes = this.scene.meshes; }
  91086. if (!this.scene.activeCamera) {
  91087. this.scene.createDefaultCamera(true, true, true);
  91088. this.camera = this.scene.activeCamera;
  91089. }
  91090. if (cameraConfig.position) {
  91091. this.camera.position.copyFromFloats(cameraConfig.position.x || 0, cameraConfig.position.y || 0, cameraConfig.position.z || 0);
  91092. }
  91093. if (cameraConfig.rotation) {
  91094. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  91095. }
  91096. this.extendClassWithConfig(this.camera, cameraConfig);
  91097. this.camera.minZ = cameraConfig.minZ || this.camera.minZ;
  91098. this.camera.maxZ = cameraConfig.maxZ || this.camera.maxZ;
  91099. if (cameraConfig.behaviors) {
  91100. for (var name_1 in cameraConfig.behaviors) {
  91101. this.setCameraBehavior(cameraConfig.behaviors[name_1], focusMeshes);
  91102. }
  91103. }
  91104. ;
  91105. var sceneExtends = this.scene.getWorldExtends(function (mesh) {
  91106. return !_this.environmentHelper || (mesh !== _this.environmentHelper.ground && mesh !== _this.environmentHelper.rootMesh && mesh !== _this.environmentHelper.skybox);
  91107. });
  91108. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  91109. var sceneDiagonalLenght = sceneDiagonal.length();
  91110. if (isFinite(sceneDiagonalLenght))
  91111. this.camera.upperRadiusLimit = sceneDiagonalLenght * 3;
  91112. };
  91113. AbstractViewer.prototype.configureLights = function (lightsConfiguration, focusMeshes) {
  91114. var _this = this;
  91115. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  91116. if (focusMeshes === void 0) { focusMeshes = this.scene.meshes; }
  91117. if (!Object.keys(lightsConfiguration).length)
  91118. return;
  91119. var lightsAvailable = this.scene.lights.map(function (light) { return light.name; });
  91120. var lightsToConfigure = Object.keys(this.configuration.lights || []);
  91121. if (Object.keys(lightsToConfigure).length !== lightsAvailable.length) {
  91122. lightsAvailable.forEach(function (lName) {
  91123. if (lightsToConfigure.indexOf(lName) === -1) {
  91124. _this.scene.getLightByName(lName).dispose();
  91125. }
  91126. });
  91127. }
  91128. Object.keys(lightsConfiguration).forEach(function (name, idx) {
  91129. var lightConfig = { type: 0 };
  91130. if (typeof lightsConfiguration[name] === 'object') {
  91131. lightConfig = lightsConfiguration[name];
  91132. }
  91133. lightConfig.name = name;
  91134. var light;
  91135. if (lightsAvailable.indexOf(name) === -1) {
  91136. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  91137. if (!constructor)
  91138. return;
  91139. light = constructor();
  91140. }
  91141. else {
  91142. light = _this.scene.getLightByName(name);
  91143. lightsAvailable = lightsAvailable.filter(function (ln) { return ln !== name; });
  91144. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  91145. light.dispose();
  91146. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  91147. if (!constructor)
  91148. return;
  91149. light = constructor();
  91150. }
  91151. }
  91152. if (lightsConfiguration[name] === false) {
  91153. light.dispose();
  91154. return;
  91155. }
  91156. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  91157. light.setEnabled(enabled);
  91158. _this.extendClassWithConfig(light, lightConfig);
  91159. if (light instanceof babylonjs_1.ShadowLight) {
  91160. if (lightConfig.target) {
  91161. if (light.setDirectionToTarget) {
  91162. var target = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.target);
  91163. light.setDirectionToTarget(target);
  91164. }
  91165. }
  91166. else if (lightConfig.direction) {
  91167. var direction = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.direction);
  91168. light.direction = direction;
  91169. }
  91170. var shadowGenerator = light.getShadowGenerator();
  91171. if (lightConfig.shadowEnabled && _this.maxShadows) {
  91172. if (!shadowGenerator) {
  91173. shadowGenerator = new babylonjs_1.ShadowGenerator(512, light);
  91174. }
  91175. _this.extendClassWithConfig(shadowGenerator, lightConfig.shadowConfig || {});
  91176. var shadownMap = shadowGenerator.getShadowMap();
  91177. if (!shadownMap)
  91178. return;
  91179. var renderList = shadownMap.renderList;
  91180. for (var index = 0; index < focusMeshes.length; index++) {
  91181. if (babylonjs_1.Tags.MatchesQuery(focusMeshes[index], 'castShadow')) {
  91182. renderList && renderList.push(focusMeshes[index]);
  91183. }
  91184. }
  91185. }
  91186. else if (shadowGenerator) {
  91187. shadowGenerator.dispose();
  91188. }
  91189. }
  91190. });
  91191. };
  91192. AbstractViewer.prototype.configureModel = function (modelConfiguration, focusMeshes) {
  91193. if (focusMeshes === void 0) { focusMeshes = this.scene.meshes; }
  91194. var meshesWithNoParent = focusMeshes.filter(function (m) { return !m.parent; });
  91195. var updateMeshesWithNoParent = function (variable, value, param) {
  91196. meshesWithNoParent.forEach(function (mesh) {
  91197. if (param) {
  91198. mesh[variable][param] = value;
  91199. }
  91200. else {
  91201. mesh[variable] = value;
  91202. }
  91203. });
  91204. };
  91205. var updateXYZ = function (variable, configValues) {
  91206. if (configValues.x !== undefined) {
  91207. updateMeshesWithNoParent(variable, configValues.x, 'x');
  91208. }
  91209. if (configValues.y !== undefined) {
  91210. updateMeshesWithNoParent(variable, configValues.y, 'y');
  91211. }
  91212. if (configValues.z !== undefined) {
  91213. updateMeshesWithNoParent(variable, configValues.z, 'z');
  91214. }
  91215. if (configValues.w !== undefined) {
  91216. updateMeshesWithNoParent(variable, configValues.w, 'w');
  91217. }
  91218. };
  91219. if (modelConfiguration.position) {
  91220. updateXYZ('position', modelConfiguration.position);
  91221. }
  91222. if (modelConfiguration.rotation) {
  91223. if (modelConfiguration.rotation.w) {
  91224. meshesWithNoParent.forEach(function (mesh) {
  91225. if (!mesh.rotationQuaternion) {
  91226. mesh.rotationQuaternion = new babylonjs_1.Quaternion();
  91227. }
  91228. });
  91229. updateXYZ('rotationQuaternion', modelConfiguration.rotation);
  91230. }
  91231. else {
  91232. updateXYZ('rotation', modelConfiguration.rotation);
  91233. }
  91234. }
  91235. if (modelConfiguration.scaling) {
  91236. updateXYZ('scaling', modelConfiguration.scaling);
  91237. }
  91238. if (modelConfiguration.castShadow) {
  91239. focusMeshes.forEach(function (mesh) {
  91240. babylonjs_1.Tags.AddTagsTo(mesh, 'castShadow');
  91241. });
  91242. }
  91243. if (modelConfiguration.normalize) {
  91244. var center = false;
  91245. var unitSize = false;
  91246. var parentIndex = void 0;
  91247. if (modelConfiguration.normalize === true) {
  91248. center = true;
  91249. unitSize = true;
  91250. parentIndex = 0;
  91251. }
  91252. else {
  91253. center = !!modelConfiguration.normalize.center;
  91254. unitSize = !!modelConfiguration.normalize.unitSize;
  91255. parentIndex = modelConfiguration.normalize.parentIndex;
  91256. }
  91257. var meshesToNormalize = [];
  91258. if (parentIndex !== undefined) {
  91259. meshesToNormalize.push(focusMeshes[parentIndex]);
  91260. }
  91261. else {
  91262. meshesToNormalize = meshesWithNoParent;
  91263. }
  91264. if (unitSize) {
  91265. meshesToNormalize.forEach(function (mesh) {
  91266. mesh.normalizeToUnitCube(true);
  91267. mesh.computeWorldMatrix(true);
  91268. });
  91269. }
  91270. if (center) {
  91271. meshesToNormalize.forEach(function (mesh) {
  91272. var boundingInfo = mesh.getHierarchyBoundingVectors(true);
  91273. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  91274. var halfSizeVec = sizeVec.scale(0.5);
  91275. var center = boundingInfo.min.add(halfSizeVec);
  91276. mesh.position = center.scale(-1);
  91277. mesh.position.y += halfSizeVec.y;
  91278. mesh.computeWorldMatrix(true);
  91279. });
  91280. }
  91281. }
  91282. };
  91283. AbstractViewer.prototype.dispose = function () {
  91284. window.removeEventListener('resize', this.resize);
  91285. if (this.sceneOptimizer) {
  91286. this.sceneOptimizer.stop();
  91287. this.sceneOptimizer.dispose();
  91288. }
  91289. if (this.scene.activeCamera) {
  91290. this.scene.activeCamera.detachControl(this.canvas);
  91291. }
  91292. this.scene.dispose();
  91293. this.engine.dispose();
  91294. this.templateManager.dispose();
  91295. };
  91296. AbstractViewer.prototype.onTemplatesLoaded = function () {
  91297. return Promise.resolve(this);
  91298. };
  91299. AbstractViewer.prototype._onTemplateLoaded = function () {
  91300. var _this = this;
  91301. return this.onTemplatesLoaded().then(function () {
  91302. var autoLoadModel = !!_this.configuration.model;
  91303. return _this.initEngine().then(function (engine) {
  91304. return _this.onEngineInitObservable.notifyObserversWithPromise(engine);
  91305. }).then(function () {
  91306. if (autoLoadModel) {
  91307. return _this.loadModel();
  91308. }
  91309. else {
  91310. return _this.scene || _this.initScene();
  91311. }
  91312. }).then(function (scene) {
  91313. return _this.onSceneInitObservable.notifyObserversWithPromise(scene);
  91314. }).then(function () {
  91315. return _this.onInitDoneObservable.notifyObserversWithPromise(_this);
  91316. }).then(function () {
  91317. return _this;
  91318. });
  91319. });
  91320. };
  91321. AbstractViewer.prototype.initEngine = function () {
  91322. this.injectCustomShaders();
  91323. var canvasElement = this.templateManager.getCanvas();
  91324. if (!canvasElement) {
  91325. return Promise.reject('Canvas element not found!');
  91326. }
  91327. var config = this.configuration.engine || {};
  91328. this.engine = new babylonjs_1.Engine(canvasElement, !!config.antialiasing, config.engineOptions);
  91329. babylonjs_1.Database.IDBStorageEnabled = false;
  91330. if (!config.disableResize) {
  91331. window.addEventListener('resize', this.resize);
  91332. }
  91333. this.engine.runRenderLoop(this.render);
  91334. if (this.configuration.engine && this.configuration.engine.adaptiveQuality) {
  91335. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  91336. this.engine.setHardwareScalingLevel(scale);
  91337. }
  91338. this.handleHardwareLimitations();
  91339. return Promise.resolve(this.engine);
  91340. };
  91341. AbstractViewer.prototype.initScene = function () {
  91342. if (this.scene) {
  91343. this.scene.dispose();
  91344. }
  91345. this.scene = new babylonjs_1.Scene(this.engine);
  91346. this.scene.createDefaultLight(true);
  91347. if (this.configuration.scene) {
  91348. this.configureScene(this.configuration.scene);
  91349. if (this.configuration.optimizer) {
  91350. this.configureOptimizer(this.configuration.optimizer);
  91351. }
  91352. }
  91353. return Promise.resolve(this.scene);
  91354. };
  91355. AbstractViewer.prototype.loadModel = function (model, clearScene) {
  91356. var _this = this;
  91357. if (model === void 0) { model = this.configuration.model; }
  91358. if (clearScene === void 0) { clearScene = true; }
  91359. var modelUrl = (typeof model === 'string') ? model : model.url;
  91360. if (!modelUrl) {
  91361. return Promise.resolve(this.scene);
  91362. }
  91363. if (this.isLoading) {
  91364. this.nextLoading = function () {
  91365. delete _this.nextLoading;
  91366. _this.loadModel(model, clearScene);
  91367. };
  91368. return Promise.resolve(this.scene);
  91369. }
  91370. this.isLoading = true;
  91371. if ((typeof model === 'string')) {
  91372. if (this.configuration.model && typeof this.configuration.model === 'object') {
  91373. this.configuration.model.url = model;
  91374. }
  91375. }
  91376. else {
  91377. if (this.configuration.model) {
  91378. deepmerge(this.configuration.model, model);
  91379. }
  91380. else {
  91381. this.configuration.model = model;
  91382. }
  91383. }
  91384. var parts = modelUrl.split('/');
  91385. var filename = parts.pop();
  91386. var base = parts.join('/') + '/';
  91387. var plugin = (typeof model === 'string') ? undefined : model.loader;
  91388. return Promise.resolve(this.scene).then(function (scene) {
  91389. if (!scene)
  91390. return _this.initScene();
  91391. if (clearScene) {
  91392. scene.meshes.forEach(function (mesh) {
  91393. if (babylonjs_1.Tags.MatchesQuery(mesh, "viewerMesh")) {
  91394. mesh.dispose();
  91395. }
  91396. });
  91397. }
  91398. return scene;
  91399. }).then(function () {
  91400. return new Promise(function (resolve, reject) {
  91401. _this.lastUsedLoader = babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, _this.scene, function (meshes) {
  91402. meshes.forEach(function (mesh) {
  91403. babylonjs_1.Tags.AddTagsTo(mesh, "viewerMesh");
  91404. });
  91405. resolve(meshes);
  91406. }, function (progressEvent) {
  91407. _this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  91408. }, function (e, m, exception) {
  91409. _this.onModelLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception }).then(function () {
  91410. reject(exception);
  91411. });
  91412. }, plugin);
  91413. _this.onLoaderInitObservable.notifyObserversWithPromise(_this.lastUsedLoader);
  91414. });
  91415. }).then(function (meshes) {
  91416. return _this.onModelLoadedObservable.notifyObserversWithPromise(meshes)
  91417. .then(function () {
  91418. _this.configureModel(_this.configuration.model || model, meshes);
  91419. _this.configureLights(_this.configuration.lights);
  91420. if (_this.configuration.camera) {
  91421. _this.configureCamera(_this.configuration.camera, meshes);
  91422. }
  91423. return _this.initEnvironment(meshes);
  91424. }).then(function () {
  91425. _this.isLoading = false;
  91426. if (_this.nextLoading) {
  91427. return _this.nextLoading();
  91428. }
  91429. return _this.scene;
  91430. });
  91431. });
  91432. };
  91433. AbstractViewer.prototype.initEnvironment = function (focusMeshes) {
  91434. if (focusMeshes === void 0) { focusMeshes = this.scene.meshes; }
  91435. this.configureEnvironment(this.configuration.skybox, this.configuration.ground);
  91436. return Promise.resolve(this.scene);
  91437. };
  91438. AbstractViewer.prototype.handleHardwareLimitations = function () {
  91439. var maxVaryingRows = this.engine.getCaps().maxVaryingVectors;
  91440. var maxFragmentSamplers = this.engine.getCaps().maxTexturesImageUnits;
  91441. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  91442. this.maxShadows = 0;
  91443. }
  91444. else {
  91445. this.maxShadows = 3;
  91446. }
  91447. var caps = this.engine.getCaps();
  91448. var linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  91449. var linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  91450. this._hdrSupport = !!(linearFloatTargets || linearHalfFloatTargets);
  91451. if (linearHalfFloatTargets) {
  91452. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_HALF_FLOAT;
  91453. this.shadowGeneratorBias = 0.002;
  91454. }
  91455. else if (linearFloatTargets) {
  91456. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_FLOAT;
  91457. this.shadowGeneratorBias = 0.001;
  91458. }
  91459. else {
  91460. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  91461. this.shadowGeneratorBias = 0.001;
  91462. }
  91463. this.defaultPipelineTextureType = this._hdrSupport ? this.defaultHighpTextureType : babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  91464. };
  91465. AbstractViewer.prototype.injectCustomShaders = function () {
  91466. var customShaders = this.configuration.customShaders;
  91467. if (!customShaders) {
  91468. return;
  91469. }
  91470. if (customShaders.shaders) {
  91471. Object.keys(customShaders.shaders).forEach(function (key) {
  91472. babylonjs_1.Effect.ShadersStore[key] = customShaders.shaders[key];
  91473. });
  91474. }
  91475. if (customShaders.includes) {
  91476. Object.keys(customShaders.includes).forEach(function (key) {
  91477. babylonjs_1.Effect.IncludesShadersStore[key] = customShaders.includes[key];
  91478. });
  91479. }
  91480. };
  91481. AbstractViewer.prototype.extendClassWithConfig = function (object, config) {
  91482. var _this = this;
  91483. if (!config)
  91484. return;
  91485. Object.keys(config).forEach(function (key) {
  91486. if (key in object && typeof object[key] !== 'function') {
  91487. if (typeof object[key] === 'object') {
  91488. _this.extendClassWithConfig(object[key], config[key]);
  91489. }
  91490. else {
  91491. if (config[key] !== undefined) {
  91492. object[key] = config[key];
  91493. }
  91494. }
  91495. }
  91496. });
  91497. };
  91498. AbstractViewer.prototype.setCameraBehavior = function (behaviorConfig, payload) {
  91499. var behavior;
  91500. var type = (typeof behaviorConfig !== "object") ? behaviorConfig : behaviorConfig.type;
  91501. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  91502. switch (type) {
  91503. case 0:
  91504. this.camera.useAutoRotationBehavior = true;
  91505. behavior = this.camera.autoRotationBehavior;
  91506. break;
  91507. case 1:
  91508. this.camera.useBouncingBehavior = true;
  91509. behavior = this.camera.bouncingBehavior;
  91510. break;
  91511. case 2:
  91512. this.camera.useFramingBehavior = true;
  91513. behavior = this.camera.framingBehavior;
  91514. break;
  91515. default:
  91516. behavior = null;
  91517. break;
  91518. }
  91519. if (behavior) {
  91520. if (typeof behaviorConfig === "object") {
  91521. this.extendClassWithConfig(behavior, behaviorConfig);
  91522. }
  91523. }
  91524. switch (type) {
  91525. case 0:
  91526. break;
  91527. case 1:
  91528. break;
  91529. case 2:
  91530. if (config.zoomOnBoundingInfo) {
  91531. var meshes = payload;
  91532. var bounding = meshes[0].getHierarchyBoundingVectors();
  91533. behavior.zoomOnBoundingInfo(bounding.min, bounding.max);
  91534. }
  91535. break;
  91536. }
  91537. };
  91538. return AbstractViewer;
  91539. }());
  91540. exports.AbstractViewer = AbstractViewer;
  91541. /***/ }),
  91542. /* 7 */
  91543. /***/ (function(module, exports) {
  91544. module.exports = "<viewer></viewer> <loading-screen></loading-screen> <overlay></overlay>";
  91545. /***/ }),
  91546. /* 8 */
  91547. /***/ (function(module, exports) {
  91548. 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}}>";
  91549. /***/ }),
  91550. /* 9 */
  91551. /***/ (function(module, exports) {
  91552. 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=="
  91553. /***/ }),
  91554. /* 10 */
  91555. /***/ (function(module, exports) {
  91556. 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>";
  91557. /***/ }),
  91558. /* 11 */
  91559. /***/ (function(module, exports) {
  91560. 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>";
  91561. /***/ }),
  91562. /* 12 */
  91563. /***/ (function(module, exports) {
  91564. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAAt0lEQVR42u2WAQbDQBBFQ9IbRtDcrrqK3LBbXrEH6OuHEPMBjPd2xHyZKtdNpcLMg11Pr7y4/YdvwIdd4jtw4BU0Rjrbz9mNzkjzgpU3wNhCvH5M3i1fKzzeK3K8V+R4r8jxTpHjlULhc0WOd8fU6e4I8y3y13tFjHel4GswwAvFSR/ZN6Zv2gjvmzbGhwqPzxUenys83is8Pld4vFac/9sy8/SVNrbgYJl8WGhsvkpoA1+pVK6ZLyLNXm2txsT5AAAAAElFTkSuQmCC"
  91565. /***/ }),
  91566. /* 13 */
  91567. /***/ (function(module, exports) {
  91568. module.exports = "Error loading the model";
  91569. /***/ }),
  91570. /* 14 */
  91571. /***/ (function(module, exports, __webpack_require__) {
  91572. (function (global, factory) {
  91573. true ? module.exports = factory() :
  91574. typeof define === 'function' && define.amd ? define(factory) :
  91575. (global.deepmerge = factory());
  91576. }(this, (function () { 'use strict';
  91577. var isMergeableObject = function isMergeableObject(value) {
  91578. return isNonNullObject(value)
  91579. && !isSpecial(value)
  91580. };
  91581. function isNonNullObject(value) {
  91582. return !!value && typeof value === 'object'
  91583. }
  91584. function isSpecial(value) {
  91585. var stringValue = Object.prototype.toString.call(value);
  91586. return stringValue === '[object RegExp]'
  91587. || stringValue === '[object Date]'
  91588. || isReactElement(value)
  91589. }
  91590. // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  91591. var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
  91592. var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
  91593. function isReactElement(value) {
  91594. return value.$$typeof === REACT_ELEMENT_TYPE
  91595. }
  91596. function emptyTarget(val) {
  91597. return Array.isArray(val) ? [] : {}
  91598. }
  91599. function cloneUnlessOtherwiseSpecified(value, optionsArgument) {
  91600. var clone = !optionsArgument || optionsArgument.clone !== false;
  91601. return (clone && isMergeableObject(value))
  91602. ? deepmerge(emptyTarget(value), value, optionsArgument)
  91603. : value
  91604. }
  91605. function defaultArrayMerge(target, source, optionsArgument) {
  91606. return target.concat(source).map(function(element) {
  91607. return cloneUnlessOtherwiseSpecified(element, optionsArgument)
  91608. })
  91609. }
  91610. function mergeObject(target, source, optionsArgument) {
  91611. var destination = {};
  91612. if (isMergeableObject(target)) {
  91613. Object.keys(target).forEach(function(key) {
  91614. destination[key] = cloneUnlessOtherwiseSpecified(target[key], optionsArgument);
  91615. });
  91616. }
  91617. Object.keys(source).forEach(function(key) {
  91618. if (!isMergeableObject(source[key]) || !target[key]) {
  91619. destination[key] = cloneUnlessOtherwiseSpecified(source[key], optionsArgument);
  91620. } else {
  91621. destination[key] = deepmerge(target[key], source[key], optionsArgument);
  91622. }
  91623. });
  91624. return destination
  91625. }
  91626. function deepmerge(target, source, optionsArgument) {
  91627. var sourceIsArray = Array.isArray(source);
  91628. var targetIsArray = Array.isArray(target);
  91629. var options = optionsArgument || { arrayMerge: defaultArrayMerge };
  91630. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  91631. if (!sourceAndTargetTypesMatch) {
  91632. return cloneUnlessOtherwiseSpecified(source, optionsArgument)
  91633. } else if (sourceIsArray) {
  91634. var arrayMerge = options.arrayMerge || defaultArrayMerge;
  91635. return arrayMerge(target, source, optionsArgument)
  91636. } else {
  91637. return mergeObject(target, source, optionsArgument)
  91638. }
  91639. }
  91640. deepmerge.all = function deepmergeAll(array, optionsArgument) {
  91641. if (!Array.isArray(array)) {
  91642. throw new Error('first argument should be an array')
  91643. }
  91644. return array.reduce(function(prev, next) {
  91645. return deepmerge(prev, next, optionsArgument)
  91646. }, {})
  91647. };
  91648. var deepmerge_1 = deepmerge;
  91649. return deepmerge_1;
  91650. })));
  91651. /***/ }),
  91652. /* 15 */
  91653. /***/ (function(module, exports, __webpack_require__) {
  91654. module.exports = __webpack_require__(16);
  91655. /***/ }),
  91656. /* 16 */
  91657. /***/ (function(module, exports, __webpack_require__) {
  91658. "use strict";
  91659. Object.defineProperty(exports, "__esModule", { value: true });
  91660. var mappers_1 = __webpack_require__(1);
  91661. exports.mapperManager = mappers_1.mapperManager;
  91662. var viewerManager_1 = __webpack_require__(4);
  91663. exports.viewerManager = viewerManager_1.viewerManager;
  91664. var defaultViewer_1 = __webpack_require__(5);
  91665. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  91666. var viewer_1 = __webpack_require__(6);
  91667. exports.AbstractViewer = viewer_1.AbstractViewer;
  91668. __webpack_require__(0);
  91669. __webpack_require__(30);
  91670. __webpack_require__(31);
  91671. var babylonjs_1 = __webpack_require__(0);
  91672. var initializer_1 = __webpack_require__(32);
  91673. exports.InitTags = initializer_1.InitTags;
  91674. babylonjs_1.PromisePolyfill.Apply();
  91675. exports.disableInit = false;
  91676. document.addEventListener("DOMContentLoaded", function (event) {
  91677. if (exports.disableInit)
  91678. return;
  91679. initializer_1.InitTags();
  91680. });
  91681. /***/ }),
  91682. /* 17 */
  91683. /***/ (function(module, exports) {
  91684. module.exports = cannon;
  91685. /***/ }),
  91686. /* 18 */
  91687. /***/ (function(module, exports, __webpack_require__) {
  91688. /**
  91689. * from OimoPhysics DEV 1.1.0a AS3
  91690. * @author Saharan / http://el-ement.com/
  91691. *
  91692. * to Oimo.js 2015 JAVASCRIPT
  91693. * @author LoTh / http://lo-th.github.io/labs/
  91694. */
  91695. var OIMO = {
  91696. REVISION: "1.2",
  91697. // Global identification of next shape.
  91698. // This will be incremented every time a shape is created.
  91699. nextID: 0,
  91700. proxyID: 0,
  91701. // BroadPhase
  91702. BR_NULL: 0,
  91703. BR_BRUTE_FORCE: 1,
  91704. BR_SWEEP_AND_PRUNE: 2,
  91705. BR_BOUNDING_VOLUME_TREE: 3,
  91706. // body type
  91707. BODY_NULL: 0,
  91708. BODY_DYNAMIC: 1,
  91709. BODY_STATIC: 2,
  91710. // shape type
  91711. SHAPE_NULL: 0,
  91712. SHAPE_SPHERE: 1,
  91713. SHAPE_BOX: 2,
  91714. SHAPE_CYLINDER: 3,
  91715. SHAPE_TETRA: 4,
  91716. // joint type
  91717. JOINT_NULL: 0,
  91718. JOINT_DISTANCE: 1,
  91719. JOINT_BALL_AND_SOCKET: 2,
  91720. JOINT_HINGE: 3,
  91721. JOINT_WHEEL: 4,
  91722. JOINT_SLIDER: 5,
  91723. JOINT_PRISMATIC: 6,
  91724. // this world scale defaut is 0.1 to 10 meters max for dynamique body
  91725. // scale all by 100 so object is between 10 to 10000 three unit.
  91726. WORLD_SCALE: 100,
  91727. INV_SCALE: 0.01,
  91728. // AABB aproximation
  91729. AABB_PROX: 0.005,
  91730. // Math function
  91731. sqrt: Math.sqrt,
  91732. abs: Math.abs,
  91733. floor: Math.floor,
  91734. cos: Math.cos,
  91735. sin: Math.sin,
  91736. acos: Math.acos,
  91737. asin: Math.asin,
  91738. atan2: Math.atan2,
  91739. round: Math.round,
  91740. pow: Math.pow,
  91741. max: Math.max,
  91742. min: Math.min,
  91743. random: Math.random,
  91744. lerp: function (a, b, percent) { return a + (b - a) * percent; },
  91745. rand: function (a, b) { return OIMO.lerp(a, b, OIMO.random()); },
  91746. randInt: function (a, b, n) { return OIMO.lerp(a, b, OIMO.random()).toFixed(n || 0) * 1; },
  91747. int: function (x) { return ~~x; },
  91748. fix: function (x, n) { return x.toFixed(n || 3, 10); },
  91749. clamp: function (value, min, max) { return OIMO.max(min, OIMO.min(max, value)); },
  91750. degtorad: 0.0174532925199432957,
  91751. radtodeg: 57.295779513082320876,
  91752. PI: 3.141592653589793,
  91753. TwoPI: 6.283185307179586,
  91754. PI90: 1.570796326794896,
  91755. PI270: 4.712388980384689,
  91756. CustomError: null,
  91757. Error: function (Class, Msg) {
  91758. if (OIMO.CustomError == null) console.error(Class, Msg);
  91759. else OIMO.CustomError.innerHTML += Class + " - " + Msg + '<br>';
  91760. }
  91761. };
  91762. var OIMO_ARRAY_TYPE;
  91763. if (!OIMO_ARRAY_TYPE) { OIMO_ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array; }
  91764. try {
  91765. (function (w) {
  91766. var perfNow;
  91767. var perfNowNames = ['now', 'webkitNow', 'msNow', 'mozNow'];
  91768. if (!!w['performance']) for (var i = 0; i < perfNowNames.length; ++i) {
  91769. var n = perfNowNames[i];
  91770. if (!!w['performance'][n]) {
  91771. perfNow = function () { return w['performance'][n]() };
  91772. break;
  91773. }
  91774. }
  91775. if (!perfNow) perfNow = Date.now;
  91776. //w.perfNow = perfNow;
  91777. OIMO.now = perfNow;
  91778. })(window);
  91779. } catch (e) { OIMO.now = function () { return 0; }; }
  91780. /**
  91781. * The class of physical computing world.
  91782. * You must be added to the world physical all computing objects
  91783. * @author saharan
  91784. * @author lo-th
  91785. */
  91786. OIMO.World = function (TimeStep, BroadPhaseType, Iterations, NoStat) {
  91787. // The time between each step
  91788. this.timeStep = TimeStep || 0.01666; // 1/60;
  91789. // The number of iterations for constraint solvers.
  91790. this.numIterations = Iterations || 8;
  91791. // It is a wide-area collision judgment that is used in order to reduce as much as possible a detailed collision judgment.
  91792. switch (BroadPhaseType || 2) {
  91793. case 1: this.broadPhase = new OIMO.BruteForceBroadPhase(); break;
  91794. case 2: default: this.broadPhase = new OIMO.SAPBroadPhase(); break;
  91795. case 3: this.broadPhase = new OIMO.DBVTBroadPhase(); break;
  91796. }
  91797. // This is the detailed information of the performance.
  91798. this.performance = null;
  91799. this.isNoStat = NoStat || false;
  91800. if (!this.isNoStat) this.performance = new OIMO.Performance(this);
  91801. // Whether the constraints randomizer is enabled or not.
  91802. this.enableRandomizer = true;
  91803. // The rigid body list
  91804. this.rigidBodies = null;
  91805. // number of rigid body
  91806. this.numRigidBodies = 0;
  91807. // The contact list
  91808. this.contacts = null;
  91809. this.unusedContacts = null;
  91810. // The number of contact
  91811. this.numContacts = 0;
  91812. // The number of contact points
  91813. this.numContactPoints = 0;
  91814. // The joint list
  91815. this.joints = null;
  91816. // The number of joints.
  91817. this.numJoints = 0;
  91818. // The number of simulation islands.
  91819. this.numIslands = 0;
  91820. // The gravity in the world.
  91821. this.gravity = new OIMO.Vec3(0, -9.80665, 0);
  91822. var numShapeTypes = 5;//4;//3;
  91823. this.detectors = [];
  91824. this.detectors.length = numShapeTypes;
  91825. var i = numShapeTypes;
  91826. while (i--) {
  91827. this.detectors[i] = [];
  91828. this.detectors[i].length = numShapeTypes;
  91829. }
  91830. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_SPHERE] = new OIMO.SphereSphereCollisionDetector();
  91831. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_BOX] = new OIMO.SphereBoxCollisionDetector(false);
  91832. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_SPHERE] = new OIMO.SphereBoxCollisionDetector(true);
  91833. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_BOX] = new OIMO.BoxBoxCollisionDetector();
  91834. // CYLINDER add
  91835. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_CYLINDER] = new OIMO.CylinderCylinderCollisionDetector();
  91836. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_BOX] = new OIMO.BoxCylinderCollisionDetector(true);
  91837. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_CYLINDER] = new OIMO.BoxCylinderCollisionDetector(false);
  91838. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_SPHERE] = new OIMO.SphereCylinderCollisionDetector(true);
  91839. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_CYLINDER] = new OIMO.SphereCylinderCollisionDetector(false);
  91840. // TETRA add
  91841. this.detectors[OIMO.SHAPE_TETRA][OIMO.SHAPE_TETRA] = new OIMO.TetraTetraCollisionDetector();
  91842. this.randX = 65535;
  91843. this.randA = 98765;
  91844. this.randB = 123456789;
  91845. //this.maxIslandRigidBodies = 64;
  91846. this.islandRigidBodies = [];
  91847. //this.islandRigidBodies.length = this.maxIslandRigidBodies;
  91848. this.islandStack = [];
  91849. //this.islandStack.length = this.maxIslandRigidBodies;
  91850. //this.maxIslandConstraints = 128;
  91851. this.islandConstraints = [];
  91852. //this.islandConstraints.length = this.maxIslandConstraints;
  91853. };
  91854. OIMO.World.prototype = {
  91855. constructor: OIMO.World,
  91856. /**
  91857. * Reset the randomizer and remove all rigid bodies, shapes, joints and any object from the world.
  91858. */
  91859. clear: function () {
  91860. this.randX = 65535;
  91861. while (this.joints !== null) {
  91862. this.removeJoint(this.joints);
  91863. }
  91864. while (this.contacts !== null) {
  91865. this.removeContact(this.contacts);
  91866. }
  91867. while (this.rigidBodies !== null) {
  91868. this.removeRigidBody(this.rigidBodies);
  91869. }
  91870. OIMO.nextID = 0;
  91871. OIMO.proxyID = 0;
  91872. },
  91873. /**
  91874. * I'll add a rigid body to the world.
  91875. * Rigid body that has been added will be the operands of each step.
  91876. * @param rigidBody Rigid body that you want to add
  91877. */
  91878. addRigidBody: function (rigidBody) {
  91879. if (rigidBody.parent) {
  91880. OIMO.Error("World", "It is not possible to be added to more than one world one of the rigid body");
  91881. }
  91882. rigidBody.parent = this;
  91883. rigidBody.awake();
  91884. for (var shape = rigidBody.shapes; shape !== null; shape = shape.next) {
  91885. this.addShape(shape);
  91886. }
  91887. if (this.rigidBodies !== null) (this.rigidBodies.prev = rigidBody).next = this.rigidBodies;
  91888. this.rigidBodies = rigidBody;
  91889. this.numRigidBodies++;
  91890. },
  91891. /**
  91892. * I will remove the rigid body from the world.
  91893. * Rigid body that has been deleted is excluded from the calculation on a step-by-step basis.
  91894. * @param rigidBody Rigid body to be removed
  91895. */
  91896. removeRigidBody: function (rigidBody) {
  91897. var remove = rigidBody;
  91898. if (remove.parent !== this) return;
  91899. remove.awake();
  91900. var js = remove.jointLink;
  91901. while (js != null) {
  91902. var joint = js.joint;
  91903. js = js.next;
  91904. this.removeJoint(joint);
  91905. }
  91906. for (var shape = rigidBody.shapes; shape !== null; shape = shape.next) {
  91907. this.removeShape(shape);
  91908. }
  91909. var prev = remove.prev;
  91910. var next = remove.next;
  91911. if (prev !== null) prev.next = next;
  91912. if (next !== null) next.prev = prev;
  91913. if (this.rigidBodies == remove) this.rigidBodies = next;
  91914. remove.prev = null;
  91915. remove.next = null;
  91916. remove.parent = null;
  91917. this.numRigidBodies--;
  91918. },
  91919. getByName: function (name) {
  91920. var result = null;
  91921. var body = this.rigidBodies;
  91922. while (body !== null) {
  91923. if (body.name !== " " && body.name === name) result = body;
  91924. body = body.next;
  91925. }
  91926. var joint = this.joints;
  91927. while (joint !== null) {
  91928. if (joint.name !== "" && joint.name === name) result = joint;
  91929. joint = joint.next;
  91930. }
  91931. return result;
  91932. },
  91933. /**
  91934. * I'll add a shape to the world..
  91935. * Add to the rigid world, and if you add a shape to a rigid body that has been added to the world,
  91936. * Shape will be added to the world automatically, please do not call from outside this method.
  91937. * @param shape Shape you want to add
  91938. */
  91939. addShape: function (shape) {
  91940. if (!shape.parent || !shape.parent.parent) {
  91941. OIMO.Error("World", "It is not possible to be added alone to shape world");
  91942. }
  91943. shape.proxy = this.broadPhase.createProxy(shape);
  91944. shape.updateProxy();
  91945. this.broadPhase.addProxy(shape.proxy);
  91946. },
  91947. /**
  91948. * I will remove the shape from the world.
  91949. * Add to the rigid world, and if you add a shape to a rigid body that has been added to the world,
  91950. * Shape will be added to the world automatically, please do not call from outside this method.
  91951. * @param shape Shape you want to delete
  91952. */
  91953. removeShape: function (shape) {
  91954. this.broadPhase.removeProxy(shape.proxy);
  91955. shape.proxy = null;
  91956. },
  91957. /**
  91958. * I'll add a joint to the world.
  91959. * Joint that has been added will be the operands of each step.
  91960. * @param shape Joint to be added
  91961. */
  91962. addJoint: function (joint) {
  91963. if (joint.parent) {
  91964. OIMO.Error("World", "It is not possible to be added to more than one world one of the joint");
  91965. }
  91966. if (this.joints != null) (this.joints.prev = joint).next = this.joints;
  91967. this.joints = joint;
  91968. joint.parent = this;
  91969. this.numJoints++;
  91970. joint.awake();
  91971. joint.attach();
  91972. },
  91973. /**
  91974. * I will remove the joint from the world.
  91975. * Joint that has been added will be the operands of each step.
  91976. * @param shape Joint to be deleted
  91977. */
  91978. removeJoint: function (joint) {
  91979. var remove = joint;
  91980. var prev = remove.prev;
  91981. var next = remove.next;
  91982. if (prev !== null) prev.next = next;
  91983. if (next !== null) next.prev = prev;
  91984. if (this.joints == remove) this.joints = next;
  91985. remove.prev = null;
  91986. remove.next = null;
  91987. this.numJoints--;
  91988. remove.awake();
  91989. remove.detach();
  91990. remove.parent = null;
  91991. },
  91992. worldscale: function (scale) {
  91993. OIMO.WORLD_SCALE = scale || 100;
  91994. OIMO.INV_SCALE = 1 / OIMO.WORLD_SCALE;
  91995. },
  91996. addContact: function (s1, s2) {
  91997. var newContact;
  91998. if (this.unusedContacts !== null) {
  91999. newContact = this.unusedContacts;
  92000. this.unusedContacts = this.unusedContacts.next;
  92001. } else {
  92002. newContact = new OIMO.Contact();
  92003. }
  92004. newContact.attach(s1, s2);
  92005. newContact.detector = this.detectors[s1.type][s2.type];
  92006. if (this.contacts) (this.contacts.prev = newContact).next = this.contacts;
  92007. this.contacts = newContact;
  92008. this.numContacts++;
  92009. },
  92010. removeContact: function (contact) {
  92011. var prev = contact.prev;
  92012. var next = contact.next;
  92013. if (next) next.prev = prev;
  92014. if (prev) prev.next = next;
  92015. if (this.contacts == contact) this.contacts = next;
  92016. contact.prev = null;
  92017. contact.next = null;
  92018. contact.detach();
  92019. contact.next = this.unusedContacts;
  92020. this.unusedContacts = contact;
  92021. this.numContacts--;
  92022. },
  92023. checkContact: function (name1, name2) {
  92024. var n1, n2;
  92025. var contact = this.contacts;
  92026. while (contact !== null) {
  92027. n1 = contact.body1.name || ' ';
  92028. n2 = contact.body2.name || ' ';
  92029. if ((n1 == name1 && n2 == name2) || (n2 == name1 && n1 == name2)) { if (contact.touching) return true; else return false; }
  92030. else contact = contact.next;
  92031. }
  92032. return false;
  92033. },
  92034. callSleep: function (body) {
  92035. if (!body.allowSleep) return false;
  92036. if (body.linearVelocity.lengthSq() > 0.04) return false;
  92037. if (body.angularVelocity.lengthSq() > 0.25) return false;
  92038. return true;
  92039. },
  92040. /**
  92041. * I will proceed only time step seconds time of World.
  92042. */
  92043. step: function () {
  92044. var time0, time1, time2, time3;
  92045. var stat = !this.isNoStat ? true : false;
  92046. if (stat) time0 = OIMO.now();
  92047. var body = this.rigidBodies;
  92048. while (body !== null) {
  92049. body.addedToIsland = false;
  92050. if (body.sleeping) {
  92051. if (
  92052. body.linearVelocity.testZero() ||
  92053. body.angularVelocity.testZero() ||
  92054. body.position.testDiff(body.sleepPosition) ||
  92055. body.orientation.testDiff(body.sleepOrientation)
  92056. ) body.awake(); // awake the body
  92057. }
  92058. body = body.next;
  92059. }
  92060. //------------------------------------------------------
  92061. // UPDATE CONTACT
  92062. //------------------------------------------------------
  92063. // broad phase
  92064. if (stat) time1 = OIMO.now();
  92065. this.broadPhase.detectPairs();
  92066. var pairs = this.broadPhase.pairs;
  92067. var i = this.broadPhase.numPairs;
  92068. //do{
  92069. while (i--) {
  92070. //for(var i=0, l=numPairs; i<l; i++){
  92071. var pair = pairs[i];
  92072. var s1;
  92073. var s2;
  92074. if (pair.shape1.id < pair.shape2.id) {
  92075. s1 = pair.shape1;
  92076. s2 = pair.shape2;
  92077. } else {
  92078. s1 = pair.shape2;
  92079. s2 = pair.shape1;
  92080. }
  92081. var link;
  92082. if (s1.numContacts < s2.numContacts) link = s1.contactLink;
  92083. else link = s2.contactLink;
  92084. var exists = false;
  92085. while (link) {
  92086. var contact = link.contact;
  92087. if (contact.shape1 == s1 && contact.shape2 == s2) {
  92088. contact.persisting = true;
  92089. exists = true;// contact already exists
  92090. break;
  92091. }
  92092. link = link.next;
  92093. }
  92094. if (!exists) {
  92095. this.addContact(s1, s2);
  92096. }
  92097. }// while(i-- >0);
  92098. if (stat) {
  92099. time2 = OIMO.now();
  92100. this.performance.broadPhaseTime = time2 - time1;
  92101. }
  92102. // update & narrow phase
  92103. this.numContactPoints = 0;
  92104. contact = this.contacts;
  92105. while (contact !== null) {
  92106. if (!contact.persisting) {
  92107. if (contact.shape1.aabb.intersectTest(contact.shape2.aabb)) {
  92108. /*var aabb1=contact.shape1.aabb;
  92109. var aabb2=contact.shape2.aabb;
  92110. if(
  92111. aabb1.minX>aabb2.maxX || aabb1.maxX<aabb2.minX ||
  92112. aabb1.minY>aabb2.maxY || aabb1.maxY<aabb2.minY ||
  92113. aabb1.minZ>aabb2.maxZ || aabb1.maxZ<aabb2.minZ
  92114. ){*/
  92115. var next = contact.next;
  92116. this.removeContact(contact);
  92117. contact = next;
  92118. continue;
  92119. }
  92120. }
  92121. var b1 = contact.body1;
  92122. var b2 = contact.body2;
  92123. if (b1.isDynamic && !b1.sleeping || b2.isDynamic && !b2.sleeping) {
  92124. contact.updateManifold();
  92125. }
  92126. this.numContactPoints += contact.manifold.numPoints;
  92127. contact.persisting = false;
  92128. contact.constraint.addedToIsland = false;
  92129. contact = contact.next;
  92130. }
  92131. if (stat) {
  92132. time3 = OIMO.now();
  92133. this.performance.narrowPhaseTime = time3 - time2;
  92134. }
  92135. //------------------------------------------------------
  92136. // SOLVE ISLANDS
  92137. //------------------------------------------------------
  92138. var invTimeStep = 1 / this.timeStep;
  92139. //var body;
  92140. var joint;
  92141. var constraint;
  92142. //var num;
  92143. for (joint = this.joints; joint !== null; joint = joint.next) {
  92144. joint.addedToIsland = false;
  92145. }
  92146. // clear old island array
  92147. this.islandRigidBodies = [];
  92148. this.islandConstraints = [];
  92149. this.islandStack = [];
  92150. // expand island buffers
  92151. /*if(this.maxIslandRigidBodies<this.numRigidBodies){
  92152. this.maxIslandRigidBodies=this.numRigidBodies<<1;
  92153. //this.maxIslandRigidBodies=this.numRigidBodies*2;
  92154. this.islandRigidBodies=[];
  92155. this.islandStack=[];
  92156. this.islandRigidBodies.length = this.maxIslandRigidBodies;
  92157. this.islandStack.length = this.maxIslandRigidBodies;
  92158. }
  92159. var numConstraints=this.numJoints+this.numContacts;
  92160. if(this.maxIslandConstraints<numConstraints){
  92161. this.maxIslandConstraints=numConstraints<<1;
  92162. //this.maxIslandConstraints=numConstraints*2;
  92163. this.islandConstraints=[];
  92164. this.islandConstraints.length = this.maxIslandConstraints;
  92165. }*/
  92166. time1 = OIMO.now();
  92167. this.numIslands = 0;
  92168. // build and solve simulation islands
  92169. for (var base = this.rigidBodies; base !== null; base = base.next) {
  92170. if (base.addedToIsland || base.isStatic || base.sleeping) continue;// ignore
  92171. if (base.isLonely()) {// update single body
  92172. if (base.isDynamic) {
  92173. base.linearVelocity.addTime(this.gravity, this.timeStep);
  92174. /*base.linearVelocity.x+=this.gravity.x*this.timeStep;
  92175. base.linearVelocity.y+=this.gravity.y*this.timeStep;
  92176. base.linearVelocity.z+=this.gravity.z*this.timeStep;*/
  92177. }
  92178. if (this.callSleep(base)) {
  92179. base.sleepTime += this.timeStep;
  92180. if (base.sleepTime > 0.5) base.sleep();
  92181. else base.updatePosition(this.timeStep);
  92182. } else {
  92183. base.sleepTime = 0;
  92184. base.updatePosition(this.timeStep);
  92185. }
  92186. this.numIslands++;
  92187. continue;
  92188. }
  92189. var islandNumRigidBodies = 0;
  92190. var islandNumConstraints = 0;
  92191. var stackCount = 1;
  92192. // add rigid body to stack
  92193. this.islandStack[0] = base;
  92194. base.addedToIsland = true;
  92195. // build an island
  92196. do {
  92197. // get rigid body from stack
  92198. body = this.islandStack[--stackCount];
  92199. this.islandStack[stackCount] = null;
  92200. body.sleeping = false;
  92201. // add rigid body to the island
  92202. this.islandRigidBodies[islandNumRigidBodies++] = body;
  92203. if (body.isStatic) continue;
  92204. // search connections
  92205. for (var cs = body.contactLink; cs !== null; cs = cs.next) {
  92206. var contact = cs.contact;
  92207. constraint = contact.constraint;
  92208. if (constraint.addedToIsland || !contact.touching) continue;// ignore
  92209. // add constraint to the island
  92210. this.islandConstraints[islandNumConstraints++] = constraint;
  92211. constraint.addedToIsland = true;
  92212. var next = cs.body;
  92213. if (next.addedToIsland) continue;
  92214. // add rigid body to stack
  92215. this.islandStack[stackCount++] = next;
  92216. next.addedToIsland = true;
  92217. }
  92218. for (var js = body.jointLink; js !== null; js = js.next) {
  92219. constraint = js.joint;
  92220. if (constraint.addedToIsland) continue;// ignore
  92221. // add constraint to the island
  92222. this.islandConstraints[islandNumConstraints++] = constraint;
  92223. constraint.addedToIsland = true;
  92224. next = js.body;
  92225. if (next.addedToIsland || !next.isDynamic) continue;
  92226. // add rigid body to stack
  92227. this.islandStack[stackCount++] = next;
  92228. next.addedToIsland = true;
  92229. }
  92230. } while (stackCount != 0);
  92231. // update velocities
  92232. var gVel = new OIMO.Vec3().addTime(this.gravity, this.timeStep);
  92233. /*var gx=this.gravity.x*this.timeStep;
  92234. var gy=this.gravity.y*this.timeStep;
  92235. var gz=this.gravity.z*this.timeStep;*/
  92236. var j = islandNumRigidBodies;
  92237. while (j--) {
  92238. //or(var j=0, l=islandNumRigidBodies; j<l; j++){
  92239. body = this.islandRigidBodies[j];
  92240. if (body.isDynamic) {
  92241. body.linearVelocity.addEqual(gVel);
  92242. /*body.linearVelocity.x+=gx;
  92243. body.linearVelocity.y+=gy;
  92244. body.linearVelocity.z+=gz;*/
  92245. }
  92246. }
  92247. // randomizing order
  92248. if (this.enableRandomizer) {
  92249. //for(var j=1, l=islandNumConstraints; j<l; j++){
  92250. j = islandNumConstraints;
  92251. while (j--) {
  92252. if (j !== 0) {
  92253. var swap = (this.randX = (this.randX * this.randA + this.randB & 0x7fffffff)) / 2147483648.0 * j | 0;
  92254. constraint = this.islandConstraints[j];
  92255. this.islandConstraints[j] = this.islandConstraints[swap];
  92256. this.islandConstraints[swap] = constraint;
  92257. }
  92258. }
  92259. }
  92260. // solve contraints
  92261. j = islandNumConstraints;
  92262. while (j--) {
  92263. //for(j=0, l=islandNumConstraints; j<l; j++){
  92264. this.islandConstraints[j].preSolve(this.timeStep, invTimeStep);// pre-solve
  92265. }
  92266. var k = this.numIterations;
  92267. while (k--) {
  92268. //for(var k=0, l=this.numIterations; k<l; k++){
  92269. j = islandNumConstraints;
  92270. while (j--) {
  92271. //for(j=0, m=islandNumConstraints; j<m; j++){
  92272. this.islandConstraints[j].solve();// main-solve
  92273. }
  92274. }
  92275. j = islandNumConstraints;
  92276. while (j--) {
  92277. //for(j=0, l=islandNumConstraints; j<l; j++){
  92278. this.islandConstraints[j].postSolve();// post-solve
  92279. this.islandConstraints[j] = null;// gc
  92280. }
  92281. // sleeping check
  92282. var sleepTime = 10;
  92283. j = islandNumRigidBodies;
  92284. while (j--) {
  92285. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  92286. body = this.islandRigidBodies[j];
  92287. if (this.callSleep(body)) {
  92288. body.sleepTime += this.timeStep;
  92289. if (body.sleepTime < sleepTime) sleepTime = body.sleepTime;
  92290. } else {
  92291. body.sleepTime = 0;
  92292. sleepTime = 0;
  92293. continue;
  92294. }
  92295. }
  92296. if (sleepTime > 0.5) {
  92297. // sleep the island
  92298. j = islandNumRigidBodies;
  92299. while (j--) {
  92300. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  92301. this.islandRigidBodies[j].sleep();
  92302. this.islandRigidBodies[j] = null;// gc
  92303. }
  92304. } else {
  92305. // update positions
  92306. j = islandNumRigidBodies;
  92307. while (j--) {
  92308. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  92309. this.islandRigidBodies[j].updatePosition(this.timeStep);
  92310. this.islandRigidBodies[j] = null;// gc
  92311. }
  92312. }
  92313. this.numIslands++;
  92314. }
  92315. if (stat) {
  92316. time2 = OIMO.now();
  92317. this.performance.solvingTime = time2 - time1;
  92318. //------------------------------------------------------
  92319. // END SIMULATION
  92320. //------------------------------------------------------
  92321. time2 = OIMO.now();
  92322. // fps update
  92323. this.performance.upfps();
  92324. this.performance.totalTime = time2 - time0;
  92325. }
  92326. }
  92327. }
  92328. /**
  92329. * The class of rigid body.
  92330. * Rigid body has the shape of a single or multiple collision processing,
  92331. * I can set the parameters individually.
  92332. * @author saharan
  92333. */
  92334. OIMO.RigidBody = function (x, y, z, rad, ax, ay, az) {
  92335. this.name = " ";
  92336. // The maximum number of shapes that can be added to a one rigid.
  92337. this.MAX_SHAPES = 64;//64;
  92338. this.prev = null;
  92339. this.next = null;
  92340. // I represent the kind of rigid body.
  92341. // Please do not change from the outside this variable.
  92342. // If you want to change the type of rigid body, always
  92343. // Please specify the type you want to set the arguments of setupMass method.
  92344. this.type = OIMO.BODY_NULL;
  92345. this.massInfo = new OIMO.MassInfo();
  92346. // It is the world coordinate of the center of gravity.
  92347. this.position = new OIMO.Vec3(x, y, z);
  92348. this.orientation = this.rotationAxisToQuad(rad || 0, ax || 0, ay || 0, az || 0);
  92349. this.newPosition = new OIMO.Vec3();
  92350. this.controlPos = false;
  92351. this.newOrientation = new OIMO.Quat();
  92352. this.newRotation = new OIMO.Vec3();
  92353. this.currentRotation = new OIMO.Vec3();
  92354. this.controlRot = false;
  92355. this.controlRotInTime = false;
  92356. // Is the translational velocity.
  92357. this.linearVelocity = new OIMO.Vec3();
  92358. // Is the angular velocity.
  92359. this.angularVelocity = new OIMO.Vec3();
  92360. // return matrix for three.js
  92361. this.matrix = new OIMO.Mat44();
  92362. //--------------------------------------------
  92363. // Please do not change from the outside this variables.
  92364. //--------------------------------------------
  92365. // It is a world that rigid body has been added.
  92366. this.parent = null;
  92367. this.contactLink = null;
  92368. this.numContacts = 0;
  92369. // An array of shapes that are included in the rigid body.
  92370. this.shapes = null;
  92371. // The number of shapes that are included in the rigid body.
  92372. this.numShapes = 0;
  92373. // It is the link array of joint that is connected to the rigid body.
  92374. this.jointLink = null;
  92375. // The number of joints that are connected to the rigid body.
  92376. this.numJoints = 0;
  92377. // It is the world coordinate of the center of gravity in the sleep just before.
  92378. this.sleepPosition = new OIMO.Vec3();
  92379. // It is a quaternion that represents the attitude of sleep just before.
  92380. this.sleepOrientation = new OIMO.Quat();
  92381. // I will show this rigid body to determine whether it is a rigid body static.
  92382. this.isStatic = false;
  92383. // I indicates that this rigid body to determine whether it is a rigid body dynamic.
  92384. this.isDynamic = false;
  92385. // It is a rotation matrix representing the orientation.
  92386. this.rotation = new OIMO.Mat33();
  92387. //--------------------------------------------
  92388. // It will be recalculated automatically from the shape, which is included.
  92389. //--------------------------------------------
  92390. // This is the weight.
  92391. this.mass = NaN;
  92392. // It is the reciprocal of the mass.
  92393. this.inverseMass = NaN;
  92394. // It is the inverse of the inertia tensor in the world system.
  92395. this.inverseInertia = new OIMO.Mat33();
  92396. // It is the inertia tensor in the initial state.
  92397. this.localInertia = new OIMO.Mat33();
  92398. // It is the inverse of the inertia tensor in the initial state.
  92399. this.inverseLocalInertia = new OIMO.Mat33();
  92400. // I indicates rigid body whether it has been added to the simulation Island.
  92401. this.addedToIsland = false;
  92402. // It shows how to sleep rigid body.
  92403. this.allowSleep = true;
  92404. // This is the time from when the rigid body at rest.
  92405. this.sleepTime = 0;
  92406. // I shows rigid body to determine whether it is a sleep state.
  92407. this.sleeping = false;
  92408. };
  92409. OIMO.RigidBody.prototype = {
  92410. constructor: OIMO.RigidBody,
  92411. /**
  92412. * I'll add a shape to rigid body.
  92413. * If you add a shape, please call the setupMass method to step up to the start of the next.
  92414. * @param shape shape to Add
  92415. */
  92416. addShape: function (shape) {
  92417. if (shape.parent) OIMO.Error("RigidBody", "It is not possible that you add to the multi-rigid body the shape of one");
  92418. if (this.shapes != null) (this.shapes.prev = shape).next = this.shapes;
  92419. this.shapes = shape;
  92420. shape.parent = this;
  92421. if (this.parent) this.parent.addShape(shape);
  92422. this.numShapes++;
  92423. },
  92424. /**
  92425. * I will delete the shape from the rigid body.
  92426. * If you delete a shape, please call the setupMass method to step up to the start of the next.
  92427. * @param shape shape to Delete
  92428. */
  92429. removeShape: function (shape) {
  92430. var remove = shape;
  92431. if (remove.parent != this) return;
  92432. var prev = remove.prev;
  92433. var next = remove.next;
  92434. if (prev != null) prev.next = next;
  92435. if (next != null) next.prev = prev;
  92436. if (this.shapes == remove) this.shapes = next;
  92437. remove.prev = null;
  92438. remove.next = null;
  92439. remove.parent = null;
  92440. if (this.parent) this.parent.removeShape(remove);
  92441. this.numShapes--;
  92442. },
  92443. remove: function () {
  92444. this.dispose();
  92445. },
  92446. dispose: function () {
  92447. this.parent.removeRigidBody(this);
  92448. },
  92449. checkContact: function (name) {
  92450. this.parent.checkContact(this.name, name);
  92451. },
  92452. /**
  92453. * Calulates mass datas(center of gravity, mass, moment inertia, etc...).
  92454. * If the parameter type is set to BODY_STATIC, the rigid body will be fixed to the space.
  92455. * If the parameter adjustPosition is set to true, the shapes' relative positions and
  92456. * the rigid body's position will be adjusted to the center of gravity.
  92457. * @param type
  92458. * @param adjustPosition
  92459. */
  92460. setupMass: function (type, AdjustPosition) {
  92461. var adjustPosition = (AdjustPosition !== undefined) ? AdjustPosition : true;
  92462. this.type = type || OIMO.BODY_DYNAMIC;
  92463. this.isDynamic = this.type == OIMO.BODY_DYNAMIC;
  92464. this.isStatic = this.type == OIMO.BODY_STATIC;
  92465. this.mass = 0;
  92466. this.localInertia.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  92467. var te = this.localInertia.elements;
  92468. //
  92469. var tmpM = new OIMO.Mat33();
  92470. var tmpV = new OIMO.Vec3();
  92471. for (var shape = this.shapes; shape != null; shape = shape.next) {
  92472. shape.calculateMassInfo(this.massInfo);
  92473. var shapeMass = this.massInfo.mass;
  92474. var relX = shape.relativePosition.x;
  92475. var relY = shape.relativePosition.y;
  92476. var relZ = shape.relativePosition.z;
  92477. /*tmpV.x+=relX*shapeMass;
  92478. tmpV.y+=relY*shapeMass;
  92479. tmpV.z+=relZ*shapeMass;*/
  92480. tmpV.addScale(shape.relativePosition, shapeMass);
  92481. this.mass += shapeMass;
  92482. this.rotateInertia(shape.relativeRotation, this.massInfo.inertia, tmpM);
  92483. this.localInertia.addEqual(tmpM);
  92484. // add offset inertia
  92485. te[0] += shapeMass * (relY * relY + relZ * relZ);
  92486. te[4] += shapeMass * (relX * relX + relZ * relZ);
  92487. te[8] += shapeMass * (relX * relX + relY * relY);
  92488. var xy = shapeMass * relX * relY;
  92489. var yz = shapeMass * relY * relZ;
  92490. var zx = shapeMass * relZ * relX;
  92491. te[1] -= xy;
  92492. te[3] -= xy;
  92493. te[2] -= yz;
  92494. te[6] -= yz;
  92495. te[5] -= zx;
  92496. te[7] -= zx;
  92497. }
  92498. this.inverseMass = 1 / this.mass;
  92499. tmpV.scaleEqual(this.inverseMass);
  92500. if (adjustPosition) {
  92501. this.position.addEqual(tmpV);
  92502. for (shape = this.shapes; shape != null; shape = shape.next) {
  92503. shape.relativePosition.subEqual(tmpV);
  92504. }
  92505. // subtract offset inertia
  92506. relX = tmpV.x;
  92507. relY = tmpV.y;
  92508. relZ = tmpV.z;
  92509. //var te = this.localInertia.elements;
  92510. te[0] -= this.mass * (relY * relY + relZ * relZ);
  92511. te[4] -= this.mass * (relX * relX + relZ * relZ);
  92512. te[8] -= this.mass * (relX * relX + relY * relY);
  92513. xy = this.mass * relX * relY;
  92514. yz = this.mass * relY * relZ;
  92515. zx = this.mass * relZ * relX;
  92516. te[1] += xy;
  92517. te[3] += xy;
  92518. te[2] += yz;
  92519. te[6] += yz;
  92520. te[5] += zx;
  92521. te[7] += zx;
  92522. }
  92523. this.inverseLocalInertia.invert(this.localInertia);
  92524. if (this.type == OIMO.BODY_STATIC) {
  92525. this.inverseMass = 0;
  92526. this.inverseLocalInertia.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  92527. }
  92528. this.syncShapes();
  92529. this.awake();
  92530. },
  92531. /**
  92532. * Awake the rigid body.
  92533. */
  92534. awake: function () {
  92535. if (!this.allowSleep || !this.sleeping) return;
  92536. this.sleeping = false;
  92537. this.sleepTime = 0;
  92538. // awake connected constraints
  92539. var cs = this.contactLink;
  92540. while (cs != null) {
  92541. cs.body.sleepTime = 0;
  92542. cs.body.sleeping = false;
  92543. cs = cs.next;
  92544. }
  92545. var js = this.jointLink;
  92546. while (js != null) {
  92547. js.body.sleepTime = 0;
  92548. js.body.sleeping = false;
  92549. js = js.next;
  92550. }
  92551. for (var shape = this.shapes; shape != null; shape = shape.next) {
  92552. shape.updateProxy();
  92553. }
  92554. },
  92555. /**
  92556. * Sleep the rigid body.
  92557. */
  92558. sleep: function () {
  92559. if (!this.allowSleep || this.sleeping) return;
  92560. this.linearVelocity.set(0, 0, 0);
  92561. this.angularVelocity.set(0, 0, 0);
  92562. this.sleepPosition.copy(this.position);
  92563. this.sleepOrientation.copy(this.orientation);
  92564. /*this.linearVelocity.x=0;
  92565. this.linearVelocity.y=0;
  92566. this.linearVelocity.z=0;
  92567. this.angularVelocity.x=0;
  92568. this.angularVelocity.y=0;
  92569. this.angularVelocity.z=0;
  92570. this.sleepPosition.x=this.position.x;
  92571. this.sleepPosition.y=this.position.y;
  92572. this.sleepPosition.z=this.position.z;*/
  92573. /*this.sleepOrientation.s=this.orientation.s;
  92574. this.sleepOrientation.x=this.orientation.x;
  92575. this.sleepOrientation.y=this.orientation.y;
  92576. this.sleepOrientation.z=this.orientation.z;*/
  92577. this.sleepTime = 0;
  92578. this.sleeping = true;
  92579. for (var shape = this.shapes; shape != null; shape = shape.next) {
  92580. shape.updateProxy();
  92581. }
  92582. },
  92583. /**
  92584. * Get whether the rigid body has not any connection with others.
  92585. * @return
  92586. */
  92587. isLonely: function () {
  92588. return this.numJoints == 0 && this.numContacts == 0;
  92589. },
  92590. /**
  92591. * The time integration of the motion of a rigid body, you can update the information such as the shape.
  92592. * This method is invoked automatically when calling the step of the World,
  92593. * There is no need to call from outside usually.
  92594. * @param timeStep time
  92595. */
  92596. updatePosition: function (timeStep) {
  92597. switch (this.type) {
  92598. case OIMO.BODY_STATIC:
  92599. this.linearVelocity.set(0, 0, 0);
  92600. this.angularVelocity.set(0, 0, 0);
  92601. // ONLY FOR TEST
  92602. if (this.controlPos) {
  92603. this.position.copy(this.newPosition);
  92604. this.controlPos = false;
  92605. }
  92606. if (this.controlRot) {
  92607. this.orientation.copy(this.newOrientation);
  92608. this.controlRot = false;
  92609. }
  92610. /*this.linearVelocity.x=0;
  92611. this.linearVelocity.y=0;
  92612. this.linearVelocity.z=0;
  92613. this.angularVelocity.x=0;
  92614. this.angularVelocity.y=0;
  92615. this.angularVelocity.z=0;*/
  92616. break;
  92617. case OIMO.BODY_DYNAMIC:
  92618. if (this.controlPos) {
  92619. this.angularVelocity.set(0, 0, 0);
  92620. this.linearVelocity.set(0, 0, 0);
  92621. this.linearVelocity.x = (this.newPosition.x - this.position.x) / timeStep;
  92622. this.linearVelocity.y = (this.newPosition.y - this.position.y) / timeStep;
  92623. this.linearVelocity.z = (this.newPosition.z - this.position.z) / timeStep;
  92624. this.controlPos = false;
  92625. }
  92626. if (this.controlRot) {
  92627. this.angularVelocity.set(0, 0, 0);
  92628. this.orientation.copy(this.newOrientation);
  92629. //var t=timeStep//*0.5;
  92630. //var q = new OIMO.Quat();
  92631. //q.sub(this.newOrientation, this.orientation);
  92632. //q.normalize(q);
  92633. /*q.s = (this.newOrientation.s - this.orientation.s)/t;
  92634. q.x = (this.newOrientation.x - this.orientation.x)/t;
  92635. q.y = (this.newOrientation.y - this.orientation.y)/t;
  92636. q.z = (this.newOrientation.z - this.orientation.z)/t;*/
  92637. //this.angularVelocity.applyQuaternion(q);
  92638. //this.angularVelocity.x = this.angularVelocity.x/t;
  92639. //this.angularVelocity.y = this.angularVelocity.y/t;
  92640. //this.angularVelocity.z = this.angularVelocity.z/t;
  92641. this.controlRot = false;
  92642. }
  92643. this.position.addTime(this.linearVelocity, timeStep);
  92644. this.orientation.addTime(this.angularVelocity, timeStep);
  92645. break;
  92646. default: OIMO.Error("RigidBody", "Invalid type.");
  92647. }
  92648. this.syncShapes();
  92649. },
  92650. rotateInertia: function (rot, inertia, out) {
  92651. var tm1 = rot.elements;
  92652. var tm2 = inertia.elements;
  92653. var a0 = tm1[0], a3 = tm1[3], a6 = tm1[6];
  92654. var a1 = tm1[1], a4 = tm1[4], a7 = tm1[7];
  92655. var a2 = tm1[2], a5 = tm1[5], a8 = tm1[8];
  92656. var b0 = tm2[0], b3 = tm2[3], b6 = tm2[6];
  92657. var b1 = tm2[1], b4 = tm2[4], b7 = tm2[7];
  92658. var b2 = tm2[2], b5 = tm2[5], b8 = tm2[8];
  92659. var e00 = a0 * b0 + a1 * b3 + a2 * b6;
  92660. var e01 = a0 * b1 + a1 * b4 + a2 * b7;
  92661. var e02 = a0 * b2 + a1 * b5 + a2 * b8;
  92662. var e10 = a3 * b0 + a4 * b3 + a5 * b6;
  92663. var e11 = a3 * b1 + a4 * b4 + a5 * b7;
  92664. var e12 = a3 * b2 + a4 * b5 + a5 * b8;
  92665. var e20 = a6 * b0 + a7 * b3 + a8 * b6;
  92666. var e21 = a6 * b1 + a7 * b4 + a8 * b7;
  92667. var e22 = a6 * b2 + a7 * b5 + a8 * b8;
  92668. var oe = out.elements;
  92669. oe[0] = e00 * a0 + e01 * a1 + e02 * a2;
  92670. oe[1] = e00 * a3 + e01 * a4 + e02 * a5;
  92671. oe[2] = e00 * a6 + e01 * a7 + e02 * a8;
  92672. oe[3] = e10 * a0 + e11 * a1 + e12 * a2;
  92673. oe[4] = e10 * a3 + e11 * a4 + e12 * a5;
  92674. oe[5] = e10 * a6 + e11 * a7 + e12 * a8;
  92675. oe[6] = e20 * a0 + e21 * a1 + e22 * a2;
  92676. oe[7] = e20 * a3 + e21 * a4 + e22 * a5;
  92677. oe[8] = e20 * a6 + e21 * a7 + e22 * a8;
  92678. },
  92679. syncShapes: function () {
  92680. var s = this.orientation.s;
  92681. var x = this.orientation.x;
  92682. var y = this.orientation.y;
  92683. var z = this.orientation.z;
  92684. var x2 = 2 * x;
  92685. var y2 = 2 * y;
  92686. var z2 = 2 * z;
  92687. var xx = x * x2;
  92688. var yy = y * y2;
  92689. var zz = z * z2;
  92690. var xy = x * y2;
  92691. var yz = y * z2;
  92692. var xz = x * z2;
  92693. var sx = s * x2;
  92694. var sy = s * y2;
  92695. var sz = s * z2;
  92696. var tr = this.rotation.elements;
  92697. tr[0] = 1 - yy - zz;
  92698. tr[1] = xy - sz;
  92699. tr[2] = xz + sy;
  92700. tr[3] = xy + sz;
  92701. tr[4] = 1 - xx - zz;
  92702. tr[5] = yz - sx;
  92703. tr[6] = xz - sy;
  92704. tr[7] = yz + sx;
  92705. tr[8] = 1 - xx - yy;
  92706. this.rotateInertia(this.rotation, this.inverseLocalInertia, this.inverseInertia);
  92707. for (var shape = this.shapes; shape != null; shape = shape.next) {
  92708. //var relPos=shape.relativePosition;
  92709. //var relRot=shape.relativeRotation;
  92710. //var rot=shape.rotation;
  92711. /*var lx=relPos.x;
  92712. var ly=relPos.y;
  92713. var lz=relPos.z;
  92714. shape.position.x=this.position.x+lx*tr[0]+ly*tr[1]+lz*tr[2];
  92715. shape.position.y=this.position.y+lx*tr[3]+ly*tr[4]+lz*tr[5];
  92716. shape.position.z=this.position.z+lx*tr[6]+ly*tr[7]+lz*tr[8];*/
  92717. shape.position.mul(this.position, shape.relativePosition, this.rotation);
  92718. //shape.rotation.mul(shape.relativeRotation,this.rotation);
  92719. // add by QuaziKb
  92720. shape.rotation.mul(this.rotation, shape.relativeRotation);
  92721. shape.updateProxy();
  92722. }
  92723. },
  92724. applyImpulse: function (position, force) {
  92725. this.linearVelocity.addScale(force, this.inverseMass);
  92726. /*this.linearVelocity.x+=force.x*this.inverseMass;
  92727. this.linearVelocity.y+=force.y*this.inverseMass;
  92728. this.linearVelocity.z+=force.z*this.inverseMass;*/
  92729. var rel = new OIMO.Vec3();
  92730. rel.sub(position, this.position).cross(rel, force).mulMat(this.inverseInertia, rel);
  92731. this.angularVelocity.addEqual(rel);
  92732. /*this.angularVelocity.x+=rel.x;
  92733. this.angularVelocity.y+=rel.y;
  92734. this.angularVelocity.z+=rel.z;*/
  92735. },
  92736. //---------------------------------------------
  92737. //
  92738. // FOR THREE JS
  92739. //
  92740. //---------------------------------------------
  92741. rotationVectToQuad: function (rot) {
  92742. var r = OIMO.EulerToAxis(rot.x * OIMO.degtorad, rot.y * OIMO.degtorad, rot.z * OIMO.degtorad);
  92743. return this.rotationAxisToQuad(r[0], r[1], r[2], r[3]);
  92744. },
  92745. rotationAxisToQuad: function (rad, ax, ay, az) { // in radian
  92746. var len = ax * ax + ay * ay + az * az;
  92747. if (len > 0) {
  92748. len = 1 / OIMO.sqrt(len);
  92749. ax *= len;
  92750. ay *= len;
  92751. az *= len;
  92752. }
  92753. var sin = OIMO.sin(rad * 0.5);
  92754. var cos = OIMO.cos(rad * 0.5);
  92755. return new OIMO.Quat(cos, sin * ax, sin * ay, sin * az);
  92756. },
  92757. //---------------------------------------------
  92758. // SET DYNAMIQUE POSITION AND ROTATION
  92759. //---------------------------------------------
  92760. setPosition: function (pos) {
  92761. this.newPosition.copy(pos).multiplyScalar(OIMO.INV_SCALE);
  92762. //this.newPosition.set(pos.x*OIMO.INV_SCALE,pos.y*OIMO.INV_SCALE,pos.z*OIMO.INV_SCALE);
  92763. this.controlPos = true;
  92764. },
  92765. setQuaternion: function (q) {
  92766. //if(this.type == this.BODY_STATIC)this.orientation.init(q.w,q.x,q.y,q.z);
  92767. this.newOrientation.set(q.x, q.y, q.z, q.w);
  92768. this.controlRot = true;
  92769. },
  92770. setRotation: function (rot) {
  92771. this.newOrientation = this.rotationVectToQuad(rot);
  92772. this.controlRot = true;
  92773. },
  92774. //---------------------------------------------
  92775. // RESET DYNAMIQUE POSITION AND ROTATION
  92776. //---------------------------------------------
  92777. resetPosition: function (x, y, z) {
  92778. this.linearVelocity.set(0, 0, 0);
  92779. this.angularVelocity.set(0, 0, 0);
  92780. this.position.set(x, y, z).multiplyScalar(OIMO.INV_SCALE);
  92781. //this.position.set( x*OIMO.INV_SCALE, y*OIMO.INV_SCALE, z*OIMO.INV_SCALE );
  92782. this.awake();
  92783. },
  92784. resetQuaternion: function (q) {
  92785. this.angularVelocity.set(0, 0, 0);
  92786. this.orientation = new OIMO.Quat(q.w, q.x, q.y, q.z);
  92787. this.awake();
  92788. },
  92789. resetRotation: function (x, y, z) {
  92790. this.angularVelocity.set(0, 0, 0);
  92791. this.orientation = this.rotationVectToQuad(new OIMO.Vec3(x, y, z));
  92792. this.awake();
  92793. },
  92794. //---------------------------------------------
  92795. // GET POSITION AND ROTATION
  92796. //---------------------------------------------
  92797. getPosition: function () {
  92798. return new OIMO.Vec3().scale(this.position, OIMO.WORLD_SCALE);
  92799. },
  92800. getRotation: function () {
  92801. return new OIMO.Euler().setFromRotationMatrix(this.rotation);
  92802. },
  92803. getQuaternion: function () {
  92804. return new OIMO.Quaternion().setFromRotationMatrix(this.rotation);
  92805. },
  92806. getMatrix: function () {
  92807. var m = this.matrix.elements;
  92808. var r, p;
  92809. if (!this.sleeping) {
  92810. // rotation matrix
  92811. r = this.rotation.elements;
  92812. m[0] = r[0]; m[1] = r[3]; m[2] = r[6]; m[3] = 0;
  92813. m[4] = r[1]; m[5] = r[4]; m[6] = r[7]; m[7] = 0;
  92814. m[8] = r[2]; m[9] = r[5]; m[10] = r[8]; m[11] = 0;
  92815. // position matrix
  92816. p = this.position;
  92817. m[12] = p.x * OIMO.WORLD_SCALE;
  92818. m[13] = p.y * OIMO.WORLD_SCALE;
  92819. m[14] = p.z * OIMO.WORLD_SCALE;
  92820. // sleep or not ?
  92821. m[15] = 0;
  92822. } else {
  92823. m[15] = 1;
  92824. }
  92825. return m;
  92826. }
  92827. };
  92828. /**
  92829. * The main class of body.
  92830. * is for simplify creation process and data access of rigidRody
  92831. * Rigid body has the shape of a single or multiple collision processing,
  92832. * all setting in object
  92833. *
  92834. * @author loth
  92835. */
  92836. OIMO.Body = function (Obj) {
  92837. var obj = Obj || {};
  92838. if (!obj.world) return;
  92839. if (obj.type === undefined) obj.type = "box";
  92840. this.name = obj.name || '';
  92841. // obsolete use world.add(obj)
  92842. this.body = obj.world.add(obj);
  92843. /*
  92844. // the world where i am
  92845. this.parent = obj.world;
  92846. // Yep my name
  92847. this.name = obj.name || '';
  92848. // I'm dynamique or not
  92849. var move = obj.move || false;
  92850. // I can sleep or not
  92851. var noSleep = obj.noSleep || false;
  92852. // My start position
  92853. var p = obj.pos || [0,0,0];
  92854. p = p.map(function(x) { return x * OIMO.INV_SCALE; });
  92855. // My size
  92856. var s = obj.size || [1,1,1];
  92857. s = s.map(function(x) { return x * OIMO.INV_SCALE; });
  92858. // My rotation in degre
  92859. var rot = obj.rot || [0,0,0];
  92860. rot = rot.map(function(x) { return x * OIMO.TO_RAD; });
  92861. var r = [];
  92862. for (var i=0; i<rot.length/3; i++){
  92863. var tmp = OIMO.EulerToAxis(rot[i+0], rot[i+1], rot[i+2]);
  92864. r.push(tmp[0]); r.push(tmp[1]); r.push(tmp[2]); r.push(tmp[3]);
  92865. }
  92866. // My physics setting
  92867. var sc = obj.sc || new OIMO.ShapeConfig();
  92868. if(obj.config){
  92869. // The density of the shape.
  92870. sc.density = obj.config[0] || 1;
  92871. // The coefficient of friction of the shape.
  92872. sc.friction = obj.config[1] || 0.4;
  92873. // The coefficient of restitution of the shape.
  92874. sc.restitution = obj.config[2] || 0.2;
  92875. // The bits of the collision groups to which the shape belongs.
  92876. sc.belongsTo = obj.config[3] || 1;
  92877. // The bits of the collision groups with which the shape collides.
  92878. sc.collidesWith = obj.config[4] || 0xffffffff;
  92879. }
  92880. if(obj.massPos){
  92881. obj.massPos = obj.massPos.map(function(x) { return x * OIMO.INV_SCALE; });
  92882. sc.relativePosition.init(obj.massPos[0], obj.massPos[1], obj.massPos[2]);
  92883. }
  92884. if(obj.massRot){
  92885. obj.massRot = obj.massRot.map(function(x) { return x * OIMO.TO_RAD; });
  92886. sc.relativeRotation = OIMO.EulerToMatrix(obj.massRot[0], obj.massRot[1], obj.massRot[2]);
  92887. }
  92888. // My rigidbody
  92889. this.body = new OIMO.RigidBody(p[0], p[1], p[2], r[0], r[1], r[2], r[3]);
  92890. // My shapes
  92891. var shapes = [];
  92892. var type = obj.type || "box";
  92893. if( typeof type === 'string' ) type = [type];// single shape
  92894. var n, n2;
  92895. for(var i=0; i<type.length; i++){
  92896. n = i*3;
  92897. n2 = i*4;
  92898. switch(type[i]){
  92899. case "sphere": shapes[i] = new OIMO.SphereShape(sc, s[n+0]); break;
  92900. case "cylinder": shapes[i] = new OIMO.BoxShape(sc, s[n+0], s[n+1], s[n+2]); break; // fake cylinder
  92901. case "box": shapes[i] = new OIMO.BoxShape(sc, s[n+0], s[n+1], s[n+2]); break;
  92902. }
  92903. this.body.addShape(shapes[i]);
  92904. if(i>0){
  92905. //shapes[i].position.init(p[0]+p[n+0], p[1]+p[n+1], p[2]+p[n+2] );
  92906. shapes[i].relativePosition = new OIMO.Vec3( p[n+0], p[n+1], p[n+2] );
  92907. if(r[n2+0]) shapes[i].relativeRotation = [ r[n2+0], r[n2+1], r[n2+2], r[n2+3] ];
  92908. }
  92909. }
  92910. // I'm static or i move
  92911. if(move){
  92912. if(obj.massPos || obj.massRot)this.body.setupMass(0x1, false);
  92913. else this.body.setupMass(0x1, true);
  92914. if(noSleep) this.body.allowSleep = false;
  92915. else this.body.allowSleep = true;
  92916. } else {
  92917. this.body.setupMass(0x2);
  92918. }
  92919. this.body.name = this.name;
  92920. this.sleeping = this.body.sleeping;
  92921. // finaly add to physics world
  92922. this.parent.addRigidBody(this.body);*/
  92923. }
  92924. OIMO.Body.prototype = {
  92925. constructor: OIMO.Body,
  92926. // SET
  92927. setPosition: function (pos) {
  92928. this.body.setPosition(pos);
  92929. },
  92930. setQuaternion: function (q) {
  92931. this.body.setQuaternion(q);
  92932. },
  92933. setRotation: function (rot) {
  92934. this.body.setRotation(rot);
  92935. },
  92936. // GET
  92937. getPosition: function () {
  92938. return this.body.getPosition();
  92939. },
  92940. getRotation: function () {
  92941. return this.body.getRotation();
  92942. },
  92943. getQuaternion: function () {
  92944. return this.body.getQuaternion();
  92945. },
  92946. getMatrix: function () {
  92947. return this.body.getMatrix();
  92948. },
  92949. getSleep: function () {
  92950. return this.body.sleeping;
  92951. },
  92952. // RESET
  92953. resetPosition: function (x, y, z) {
  92954. this.body.resetPosition(x, y, z);
  92955. },
  92956. resetRotation: function (x, y, z) {
  92957. this.body.resetRotation(x, y, z);
  92958. },
  92959. // force wakeup
  92960. awake: function () {
  92961. this.body.awake();
  92962. },
  92963. // remove rigidbody
  92964. remove: function () {
  92965. this.body.dispose();
  92966. //this.parent.removeRigidBody(this.body);
  92967. },
  92968. // test if this object hit another
  92969. checkContact: function (name) {
  92970. this.body.checkContact(name);
  92971. //this.parent.checkContact(this.name, name);
  92972. }
  92973. }
  92974. /**
  92975. * The main class of link.
  92976. * is for simplify creation process and data access of Joint
  92977. * all setting in object
  92978. *
  92979. * @author loth
  92980. */
  92981. OIMO.Link = function (Obj) {
  92982. var obj = Obj || {};
  92983. if (!obj.world) return;
  92984. if (obj.type === undefined) obj.type = "jointHinge";
  92985. this.name = obj.name || '';
  92986. // obsolete use world.add(obj)
  92987. this.joint = obj.world.add(obj);
  92988. // the world where i am
  92989. /*this.parent = obj.world;
  92990. this.name = obj.name || '';
  92991. var type = obj.type || "jointHinge";
  92992. var axe1 = obj.axe1 || [1,0,0];
  92993. var axe2 = obj.axe2 || [1,0,0];
  92994. var pos1 = obj.pos1 || [0,0,0];
  92995. var pos2 = obj.pos2 || [0,0,0];
  92996. pos1 = pos1.map(function(x){ return x * OIMO.INV_SCALE; });
  92997. pos2 = pos2.map(function(x){ return x * OIMO.INV_SCALE; });
  92998. var min, max;
  92999. if(type==="jointDistance"){
  93000. min = obj.min || 0;
  93001. max = obj.max || 10;
  93002. min = min*OIMO.INV_SCALE;
  93003. max = max*OIMO.INV_SCALE;
  93004. }else{
  93005. min = obj.min || 57.29578;
  93006. max = obj.max || 0;
  93007. min = min*OIMO.TO_RAD;
  93008. max = max*OIMO.TO_RAD;
  93009. }
  93010. var limit = obj.limit || null;
  93011. var spring = obj.spring || null;
  93012. var motor = obj.motor || null;
  93013. // joint setting
  93014. var jc = new OIMO.JointConfig();
  93015. jc.allowCollision = obj.collision || false;;
  93016. jc.localAxis1.init(axe1[0], axe1[1], axe1[2]);
  93017. jc.localAxis2.init(axe2[0], axe2[1], axe2[2]);
  93018. jc.localAnchorPoint1.init(pos1[0], pos1[1], pos1[2]);
  93019. jc.localAnchorPoint2.init(pos2[0], pos2[1], pos2[2]);
  93020. if (typeof obj.body1 == 'string' || obj.body1 instanceof String) obj.body1 = obj.world.getByName(obj.body1);
  93021. if (typeof obj.body2 == 'string' || obj.body2 instanceof String) obj.body2 = obj.world.getByName(obj.body2);
  93022. jc.body1 = obj.body1;
  93023. jc.body2 = obj.body2;
  93024. switch(type){
  93025. case "jointDistance": this.joint = new OIMO.DistanceJoint(jc, min, max);
  93026. if(spring !== null) this.joint.limitMotor.setSpring(spring[0], spring[1]);
  93027. if(motor !== null) this.joint.limitMotor.setSpring(motor[0], motor[1]);
  93028. break;
  93029. case "jointHinge": this.joint = new OIMO.HingeJoint(jc, min, max);
  93030. if(spring !== null) this.joint.limitMotor.setSpring(spring[0], spring[1]);// soften the joint ex: 100, 0.2
  93031. if(motor !== null) this.joint.limitMotor.setSpring(motor[0], motor[1]);
  93032. break;
  93033. case "jointPrisme": this.joint = new OIMO.PrismaticJoint(jc, min, max); break;
  93034. case "jointSlide": this.joint = new OIMO.SliderJoint(jc, min, max); break;
  93035. case "jointBall": this.joint = new OIMO.BallAndSocketJoint(jc); break;
  93036. case "jointWheel": this.joint = new OIMO.WheelJoint(jc);
  93037. if(limit !== null) this.joint.rotationalLimitMotor1.setLimit(limit[0], limit[1]);
  93038. if(spring !== null) this.joint.rotationalLimitMotor1.setSpring(spring[0], spring[1]);
  93039. if(motor !== null) this.joint.rotationalLimitMotor1.setSpring(motor[0], motor[1]);
  93040. break;
  93041. }
  93042. this.joint.name = this.name;
  93043. // finaly add to physics world
  93044. this.parent.addJoint(this.joint);*/
  93045. }
  93046. OIMO.Link.prototype = {
  93047. constructor: OIMO.Link,
  93048. getPosition: function () {
  93049. // array of two vect3 [point1, point2]
  93050. return this.joint.getPosition();
  93051. },
  93052. getMatrix: function () {
  93053. return this.joint.getMatrix();
  93054. },
  93055. // remove joint
  93056. remove: function () {
  93057. this.joint.dispose();
  93058. //this.parent.removeJoint(this.joint);
  93059. },
  93060. // force wakeup linked body
  93061. awake: function () {
  93062. this.joint.awake();
  93063. }
  93064. }
  93065. /**
  93066. * The Dictionary class for testing
  93067. * @author lo-th
  93068. */
  93069. OIMO.Dictionary = function () {
  93070. this.data = {};
  93071. this.keys = [];
  93072. };
  93073. OIMO.Dictionary.prototype = {
  93074. constructor: OIMO.Dictionary,
  93075. set: function (value) {
  93076. var key = value.id;
  93077. if (!this.get[key]) this.keys.push(key);
  93078. this.data[key] = value;
  93079. },
  93080. get: function (id) {
  93081. return this.data[id];
  93082. },
  93083. del: function (value) {
  93084. var k = this.keys;
  93085. var n = k.indexOf(value.id);
  93086. if (n > -1) {
  93087. delete this.data[k[n]];
  93088. k.splice(n, 1);
  93089. }
  93090. },
  93091. reset: function () {
  93092. var data = this.data, keys = this.keys, key;
  93093. while (keys.length > 0) {
  93094. key = keys.pop();
  93095. delete data[key];
  93096. }
  93097. }
  93098. };
  93099. OIMO.Performance = function (world) {
  93100. this.parent = world;
  93101. this.infos = new OIMO_ARRAY_TYPE(13);
  93102. this.f = [0, 0, 0];
  93103. this.types = ['None', 'BruteForce', 'Sweep & Prune', 'Bounding Volume Tree'];
  93104. this.broadPhase = this.types[this.parent.broadPhase.types];
  93105. this.version = OIMO.REVISION;
  93106. this.fps = 0;
  93107. this.broadPhaseTime = 0;
  93108. this.narrowPhaseTime = 0;
  93109. this.solvingTime = 0;
  93110. //this.updatingTime = 0;
  93111. this.totalTime = 0;
  93112. };
  93113. OIMO.Performance.prototype = {
  93114. upfps: function () {
  93115. this.f[1] = Date.now();
  93116. 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]++;
  93117. },
  93118. updatingTime: function () {
  93119. return OIMO.fix(this.totalTime - (this.broadPhaseTime + this.narrowPhaseTime + this.solvingTime));
  93120. },
  93121. show: function () {
  93122. var info = [
  93123. "Oimo.js " + this.version + "<br>",
  93124. this.broadPhase + "<br><br>",
  93125. "FPS: " + this.fps + " fps<br><br>",
  93126. "rigidbody " + this.parent.numRigidBodies + "<br>",
  93127. "contact &nbsp;&nbsp;" + this.parent.numContacts + "<br>",
  93128. "ct-point &nbsp;" + this.parent.numContactPoints + "<br>",
  93129. "paircheck " + this.parent.broadPhase.numPairChecks + "<br>",
  93130. "island &nbsp;&nbsp;&nbsp;" + this.parent.numIslands + "<br><br>",
  93131. "Time in milliseconde<br><br>",
  93132. "broad-phase &nbsp;" + OIMO.fix(this.broadPhaseTime) + "<br>",
  93133. "narrow-phase " + OIMO.fix(this.narrowPhaseTime) + "<br>",
  93134. "solving &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + OIMO.fix(this.solvingTime) + "<br>",
  93135. "total &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + OIMO.fix(this.totalTime) + "<br>",
  93136. "updating &nbsp;&nbsp;&nbsp;&nbsp;" + this.updatingTime() + "<br>"
  93137. ].join("\n");
  93138. return info;
  93139. },
  93140. toArray: function () {
  93141. this.infos[0] = this.parent.broadPhase.types;
  93142. this.infos[1] = this.parent.numRigidBodies;
  93143. this.infos[2] = this.parent.numContacts;
  93144. this.infos[3] = this.parent.broadPhase.numPairChecks;
  93145. this.infos[4] = this.parent.numContactPoints;
  93146. this.infos[5] = this.parent.numIslands;
  93147. this.infos[6] = this.broadPhaseTime;
  93148. this.infos[7] = this.narrowPhaseTime;
  93149. this.infos[8] = this.solvingTime;
  93150. this.infos[9] = this.updatingTime();
  93151. this.infos[10] = this.totalTime;
  93152. this.infos[11] = this.fps;
  93153. return this.infos;
  93154. }
  93155. };
  93156. OIMO.Mat44 = function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  93157. this.elements = new OIMO_ARRAY_TYPE(16);
  93158. var te = this.elements;
  93159. te[0] = (n11 !== undefined) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  93160. te[1] = n21 || 0; te[5] = (n22 !== undefined) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  93161. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = (n33 !== undefined) ? n33 : 1; te[14] = n34 || 0;
  93162. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = (n44 !== undefined) ? n44 : 1;
  93163. };
  93164. OIMO.Mat44.prototype = {
  93165. constructor: OIMO.Mat44,
  93166. set: function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  93167. var te = this.elements;
  93168. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  93169. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  93170. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  93171. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  93172. return this;
  93173. }/*,
  93174. extractRotation: function () {
  93175. var v1 = new THREE.Vector3();
  93176. return function ( m ) {
  93177. var te = this.elements;
  93178. var me = m.elements;
  93179. var scaleX = 1 / v1.set( me[ 0 ], me[ 1 ], me[ 2 ] ).length();
  93180. var scaleY = 1 / v1.set( me[ 4 ], me[ 5 ], me[ 6 ] ).length();
  93181. var scaleZ = 1 / v1.set( me[ 8 ], me[ 9 ], me[ 10 ] ).length();
  93182. te[ 0 ] = me[ 0 ] * scaleX;
  93183. te[ 1 ] = me[ 1 ] * scaleX;
  93184. te[ 2 ] = me[ 2 ] * scaleX;
  93185. te[ 4 ] = me[ 4 ] * scaleY;
  93186. te[ 5 ] = me[ 5 ] * scaleY;
  93187. te[ 6 ] = me[ 6 ] * scaleY;
  93188. te[ 8 ] = me[ 8 ] * scaleZ;
  93189. te[ 9 ] = me[ 9 ] * scaleZ;
  93190. te[ 10 ] = me[ 10 ] * scaleZ;
  93191. return this;
  93192. };
  93193. }() */
  93194. }
  93195. OIMO.Mat33 = function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  93196. this.elements = new OIMO_ARRAY_TYPE(9);
  93197. var te = this.elements;
  93198. this.init(
  93199. (e00 !== undefined) ? e00 : 1, e01 || 0, e02 || 0,
  93200. e10 || 0, (e11 !== undefined) ? e11 : 1, e12 || 0,
  93201. e20 || 0, e21 || 0, (e22 !== undefined) ? e22 : 1
  93202. );
  93203. };
  93204. OIMO.Mat33.prototype = {
  93205. constructor: OIMO.Mat33,
  93206. set: function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  93207. var te = this.elements;
  93208. te[0] = e00; te[1] = e01; te[2] = e02;
  93209. te[3] = e10; te[4] = e11; te[5] = e12;
  93210. te[6] = e20; te[7] = e21; te[8] = e22;
  93211. return this;
  93212. },
  93213. init: function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  93214. var te = this.elements;
  93215. te[0] = e00; te[1] = e01; te[2] = e02;
  93216. te[3] = e10; te[4] = e11; te[5] = e12;
  93217. te[6] = e20; te[7] = e21; te[8] = e22;
  93218. return this;
  93219. },
  93220. multiply: function (s) {
  93221. var te = this.elements;
  93222. te[0] *= s; te[1] *= s; te[2] *= s;
  93223. te[3] *= s; te[4] *= s; te[5] *= s;
  93224. te[6] *= s; te[7] *= s; te[8] *= s;
  93225. return this;
  93226. },
  93227. add: function (m1, m2) {
  93228. var te = this.elements, tem1 = m1.elements, tem2 = m2.elements;
  93229. te[0] = tem1[0] + tem2[0]; te[1] = tem1[1] + tem2[1]; te[2] = tem1[2] + tem2[2];
  93230. te[3] = tem1[3] + tem2[3]; te[4] = tem1[4] + tem2[4]; te[5] = tem1[5] + tem2[5];
  93231. te[6] = tem1[6] + tem2[6]; te[7] = tem1[7] + tem2[7]; te[8] = tem1[8] + tem2[8];
  93232. return this;
  93233. },
  93234. addEqual: function (m) {
  93235. var te = this.elements, tem = m.elements;
  93236. te[0] += tem[0]; te[1] += tem[1]; te[2] += tem[2];
  93237. te[3] += tem[3]; te[4] += tem[4]; te[5] += tem[5];
  93238. te[6] += tem[6]; te[7] += tem[7]; te[8] += tem[8];
  93239. return this;
  93240. },
  93241. sub: function (m1, m2) {
  93242. var te = this.elements, tem1 = m1.elements, tem2 = m2.elements;
  93243. te[0] = tem1[0] - tem2[0]; te[1] = tem1[1] - tem2[1]; te[2] = tem1[2] - tem2[2];
  93244. te[3] = tem1[3] - tem2[3]; te[4] = tem1[4] - tem2[4]; te[5] = tem1[5] - tem2[5];
  93245. te[6] = tem1[6] - tem2[6]; te[7] = tem1[7] - tem2[7]; te[8] = tem1[8] - tem2[8];
  93246. return this;
  93247. },
  93248. subEqual: function (m) {
  93249. var te = this.elements, tem = m.elements;
  93250. te[0] -= tem[0]; te[1] -= tem[1]; te[2] -= tem[2];
  93251. te[3] -= tem[3]; te[4] -= tem[4]; te[5] -= tem[5];
  93252. te[6] -= tem[6]; te[7] -= tem[7]; te[8] -= tem[8];
  93253. return this;
  93254. },
  93255. scale: function (m, s) {
  93256. var te = this.elements, tm = m.elements;
  93257. te[0] = tm[0] * s; te[1] = tm[1] * s; te[2] = tm[2] * s;
  93258. te[3] = tm[3] * s; te[4] = tm[4] * s; te[5] = tm[5] * s;
  93259. te[6] = tm[6] * s; te[7] = tm[7] * s; te[8] = tm[8] * s;
  93260. return this;
  93261. },
  93262. scaleEqual: function (s) {
  93263. var te = this.elements;
  93264. te[0] *= s; te[1] *= s; te[2] *= s;
  93265. te[3] *= s; te[4] *= s; te[5] *= s;
  93266. te[6] *= s; te[7] *= s; te[8] *= s;
  93267. return this;
  93268. },
  93269. mul: function (m1, m2) {
  93270. var te = this.elements, tm1 = m1.elements, tm2 = m2.elements,
  93271. a0 = tm1[0], a3 = tm1[3], a6 = tm1[6],
  93272. a1 = tm1[1], a4 = tm1[4], a7 = tm1[7],
  93273. a2 = tm1[2], a5 = tm1[5], a8 = tm1[8],
  93274. b0 = tm2[0], b3 = tm2[3], b6 = tm2[6],
  93275. b1 = tm2[1], b4 = tm2[4], b7 = tm2[7],
  93276. b2 = tm2[2], b5 = tm2[5], b8 = tm2[8];
  93277. te[0] = a0 * b0 + a1 * b3 + a2 * b6;
  93278. te[1] = a0 * b1 + a1 * b4 + a2 * b7;
  93279. te[2] = a0 * b2 + a1 * b5 + a2 * b8;
  93280. te[3] = a3 * b0 + a4 * b3 + a5 * b6;
  93281. te[4] = a3 * b1 + a4 * b4 + a5 * b7;
  93282. te[5] = a3 * b2 + a4 * b5 + a5 * b8;
  93283. te[6] = a6 * b0 + a7 * b3 + a8 * b6;
  93284. te[7] = a6 * b1 + a7 * b4 + a8 * b7;
  93285. te[8] = a6 * b2 + a7 * b5 + a8 * b8;
  93286. return this;
  93287. },
  93288. mulScale: function (m, sx, sy, sz, Prepend) {
  93289. var prepend = Prepend || false;
  93290. var te = this.elements, tm = m.elements;
  93291. if (prepend) {
  93292. te[0] = sx * tm[0]; te[1] = sx * tm[1]; te[2] = sx * tm[2];
  93293. te[3] = sy * tm[3]; te[4] = sy * tm[4]; te[5] = sy * tm[5];
  93294. te[6] = sz * tm[6]; te[7] = sz * tm[7]; te[8] = sz * tm[8];
  93295. } else {
  93296. te[0] = tm[0] * sx; te[1] = tm[1] * sy; te[2] = tm[2] * sz;
  93297. te[3] = tm[3] * sx; te[4] = tm[4] * sy; te[5] = tm[5] * sz;
  93298. te[6] = tm[6] * sx; te[7] = tm[7] * sy; te[8] = tm[8] * sz;
  93299. }
  93300. return this;
  93301. },
  93302. mulRotate: function (m, rad, ax, ay, az, Prepend) {
  93303. var prepend = Prepend || false;
  93304. var s = OIMO.sin(rad);
  93305. var c = OIMO.cos(rad);
  93306. var c1 = 1 - c;
  93307. var r00 = ax * ax * c1 + c;
  93308. var r01 = ax * ay * c1 - az * s;
  93309. var r02 = ax * az * c1 + ay * s;
  93310. var r10 = ay * ax * c1 + az * s;
  93311. var r11 = ay * ay * c1 + c;
  93312. var r12 = ay * az * c1 - ax * s;
  93313. var r20 = az * ax * c1 - ay * s;
  93314. var r21 = az * ay * c1 + ax * s;
  93315. var r22 = az * az * c1 + c;
  93316. var tm = m.elements;
  93317. var a0 = tm[0], a3 = tm[3], a6 = tm[6];
  93318. var a1 = tm[1], a4 = tm[4], a7 = tm[7];
  93319. var a2 = tm[2], a5 = tm[5], a8 = tm[8];
  93320. var te = this.elements;
  93321. if (prepend) {
  93322. te[0] = r00 * a0 + r01 * a3 + r02 * a6;
  93323. te[1] = r00 * a1 + r01 * a4 + r02 * a7;
  93324. te[2] = r00 * a2 + r01 * a5 + r02 * a8;
  93325. te[3] = r10 * a0 + r11 * a3 + r12 * a6;
  93326. te[4] = r10 * a1 + r11 * a4 + r12 * a7;
  93327. te[5] = r10 * a2 + r11 * a5 + r12 * a8;
  93328. te[6] = r20 * a0 + r21 * a3 + r22 * a6;
  93329. te[7] = r20 * a1 + r21 * a4 + r22 * a7;
  93330. te[8] = r20 * a2 + r21 * a5 + r22 * a8;
  93331. } else {
  93332. te[0] = a0 * r00 + a1 * r10 + a2 * r20;
  93333. te[1] = a0 * r01 + a1 * r11 + a2 * r21;
  93334. te[2] = a0 * r02 + a1 * r12 + a2 * r22;
  93335. te[3] = a3 * r00 + a4 * r10 + a5 * r20;
  93336. te[4] = a3 * r01 + a4 * r11 + a5 * r21;
  93337. te[5] = a3 * r02 + a4 * r12 + a5 * r22;
  93338. te[6] = a6 * r00 + a7 * r10 + a8 * r20;
  93339. te[7] = a6 * r01 + a7 * r11 + a8 * r21;
  93340. te[8] = a6 * r02 + a7 * r12 + a8 * r22;
  93341. }
  93342. return this;
  93343. },
  93344. transpose: function (m) {
  93345. var te = this.elements, tm = m.elements;
  93346. te[0] = tm[0]; te[1] = tm[3]; te[2] = tm[6];
  93347. te[3] = tm[1]; te[4] = tm[4]; te[5] = tm[7];
  93348. te[6] = tm[2]; te[7] = tm[5]; te[8] = tm[8];
  93349. return this;
  93350. },
  93351. setQuat: function (q) {
  93352. var te = this.elements,
  93353. x2 = 2 * q.x, y2 = 2 * q.y, z2 = 2 * q.z,
  93354. xx = q.x * x2, yy = q.y * y2, zz = q.z * z2,
  93355. xy = q.x * y2, yz = q.y * z2, xz = q.x * z2,
  93356. sx = q.s * x2, sy = q.s * y2, sz = q.s * z2;
  93357. te[0] = 1 - yy - zz;
  93358. te[1] = xy - sz;
  93359. te[2] = xz + sy;
  93360. te[3] = xy + sz;
  93361. te[4] = 1 - xx - zz;
  93362. te[5] = yz - sx;
  93363. te[6] = xz - sy;
  93364. te[7] = yz + sx;
  93365. te[8] = 1 - xx - yy;
  93366. return this;
  93367. },
  93368. invert: function (m) {
  93369. var te = this.elements, tm = m.elements,
  93370. a0 = tm[0], a3 = tm[3], a6 = tm[6],
  93371. a1 = tm[1], a4 = tm[4], a7 = tm[7],
  93372. a2 = tm[2], a5 = tm[5], a8 = tm[8],
  93373. b01 = a4 * a8 - a7 * a5,
  93374. b11 = a7 * a2 - a1 * a8,
  93375. b21 = a1 * a5 - a4 * a2,
  93376. dt = a0 * (b01) + a3 * (b11) + a6 * (b21);
  93377. if (dt != 0) { dt = 1.0 / dt; }
  93378. te[0] = dt * b01;//(a4*a8 - a5*a7);
  93379. te[1] = dt * b11;//(a2*a7 - a1*a8);
  93380. te[2] = dt * b21;//(a1*a5 - a2*a4);
  93381. te[3] = dt * (a5 * a6 - a3 * a8);
  93382. te[4] = dt * (a0 * a8 - a2 * a6);
  93383. te[5] = dt * (a2 * a3 - a0 * a5);
  93384. te[6] = dt * (a3 * a7 - a4 * a6);
  93385. te[7] = dt * (a1 * a6 - a0 * a7);
  93386. te[8] = dt * (a0 * a4 - a1 * a3);
  93387. return this;
  93388. },
  93389. /*copy: function(m){
  93390. var te = this.elements, tem = m.elements;
  93391. te[0] = tem[0]; te[1] = tem[1]; te[2] = tem[2];
  93392. te[3] = tem[3]; te[4] = tem[4]; te[5] = tem[5];
  93393. te[6] = tem[6]; te[7] = tem[7]; te[8] = tem[8];
  93394. return this;
  93395. },*/
  93396. toEuler: function () { // not work !!
  93397. function clamp(x) {
  93398. return OIMO.min(OIMO.max(x, -1), 1);
  93399. }
  93400. var te = this.elements;
  93401. var m11 = te[0], m12 = te[3], m13 = te[6];
  93402. var m21 = te[1], m22 = te[4], m23 = te[7];
  93403. var m31 = te[2], m32 = te[5], m33 = te[8];
  93404. var p = new OIMO.Vec3();
  93405. var d = new OIMO.Quat();
  93406. var s;
  93407. p.y = OIMO.asin(clamp(m13));
  93408. if (OIMO.abs(m13) < 0.99999) {
  93409. p.x = OIMO.atan2(-m23, m33);
  93410. p.z = OIMO.atan2(-m12, m11);
  93411. } else {
  93412. p.x = OIMO.atan2(m32, m22);
  93413. p.z = 0;
  93414. }
  93415. return p;
  93416. },
  93417. /*clone: function(){
  93418. var te = this.elements;
  93419. return new OIMO.Mat33(
  93420. te[0], te[1], te[2],
  93421. te[3], te[4], te[5],
  93422. te[6], te[7], te[8]
  93423. );
  93424. },*/
  93425. toString: function () {
  93426. var te = this.elements;
  93427. var text =
  93428. "Mat33|" + te[0].toFixed(4) + ", " + te[1].toFixed(4) + ", " + te[2].toFixed(4) + "|\n" +
  93429. " |" + te[3].toFixed(4) + ", " + te[4].toFixed(4) + ", " + te[5].toFixed(4) + "|\n" +
  93430. " |" + te[6].toFixed(4) + ", " + te[7].toFixed(4) + ", " + te[8].toFixed(4) + "|";
  93431. return text;
  93432. },
  93433. // OK
  93434. multiplyScalar: function (s) {
  93435. var te = this.elements;
  93436. te[0] *= s; te[3] *= s; te[6] *= s;
  93437. te[1] *= s; te[4] *= s; te[7] *= s;
  93438. te[2] *= s; te[5] *= s; te[8] *= s;
  93439. return this;
  93440. },
  93441. identity: function () {
  93442. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  93443. return this;
  93444. },
  93445. clone: function () {
  93446. return new this.constructor().fromArray(this.elements);
  93447. },
  93448. copy: function (m) {
  93449. var me = m.elements;
  93450. this.set(
  93451. me[0], me[3], me[6],
  93452. me[1], me[4], me[7],
  93453. me[2], me[5], me[8]
  93454. );
  93455. return this;
  93456. },
  93457. fromArray: function (array) {
  93458. this.elements.set(array);
  93459. return this;
  93460. },
  93461. toArray: function () {
  93462. var te = this.elements;
  93463. return [
  93464. te[0], te[1], te[2],
  93465. te[3], te[4], te[5],
  93466. te[6], te[7], te[8]
  93467. ];
  93468. }
  93469. };
  93470. OIMO.Quat = function (s, x, y, z) {
  93471. this.s = (s !== undefined) ? s : 1;
  93472. this.x = x || 0;
  93473. this.y = y || 0;
  93474. this.z = z || 0;
  93475. };
  93476. OIMO.Quat.prototype = {
  93477. constructor: OIMO.Quat,
  93478. set: function (x, y, z, w) {
  93479. this.x = x;
  93480. this.y = y;
  93481. this.z = z;
  93482. this.s = w;
  93483. return this;
  93484. },
  93485. init: function (s, x, y, z) {
  93486. this.s = (s !== undefined) ? s : 1;
  93487. this.x = x || 0;
  93488. this.y = y || 0;
  93489. this.z = z || 0;
  93490. return this;
  93491. },
  93492. add: function (q1, q2) {
  93493. this.s = q1.s + q2.s;
  93494. this.x = q1.x + q2.x;
  93495. this.y = q1.y + q2.y;
  93496. this.z = q1.z + q2.z;
  93497. return this;
  93498. },
  93499. addTime: function (v, t) {
  93500. var x = v.x;
  93501. var y = v.y;
  93502. var z = v.z;
  93503. var qs = this.s;
  93504. var qx = this.x;
  93505. var qy = this.y;
  93506. var qz = this.z;
  93507. t *= 0.5;
  93508. var ns = (-x * qx - y * qy - z * qz) * t;
  93509. var nx = (x * qs + y * qz - z * qy) * t;
  93510. var ny = (-x * qz + y * qs + z * qx) * t;
  93511. var nz = (x * qy - y * qx + z * qs) * t;
  93512. qs += ns;
  93513. qx += nx;
  93514. qy += ny;
  93515. qz += nz;
  93516. var s = 1 / OIMO.sqrt(qs * qs + qx * qx + qy * qy + qz * qz);
  93517. this.s = qs * s;
  93518. this.x = qx * s;
  93519. this.y = qy * s;
  93520. this.z = qz * s;
  93521. return this;
  93522. },
  93523. sub: function (q1, q2) {
  93524. this.s = q1.s - q2.s;
  93525. this.x = q1.x - q2.x;
  93526. this.y = q1.y - q2.y;
  93527. this.z = q1.z - q2.z;
  93528. return this;
  93529. },
  93530. scale: function (q, s) {
  93531. this.s = q.s * s;
  93532. this.x = q.x * s;
  93533. this.y = q.y * s;
  93534. this.z = q.z * s;
  93535. return this;
  93536. },
  93537. mul: function (q1, q2) {
  93538. var ax = q1.x, ay = q1.y, az = q1.z, as = q1.s,
  93539. bx = q2.x, by = q2.y, bz = q2.z, bs = q2.s;
  93540. this.x = ax * bs + as * bx + ay * bz - az * by;
  93541. this.y = ay * bs + as * by + az * bx - ax * bz;
  93542. this.z = az * bs + as * bz + ax * by - ay * bx;
  93543. this.s = as * bs - ax * bx - ay * by - az * bz;
  93544. return this;
  93545. },
  93546. arc: function (v1, v2) {
  93547. var x1 = v1.x;
  93548. var y1 = v1.y;
  93549. var z1 = v1.z;
  93550. var x2 = v2.x;
  93551. var y2 = v2.y;
  93552. var z2 = v2.z;
  93553. var d = x1 * x2 + y1 * y2 + z1 * z2;
  93554. if (d == -1) {
  93555. x2 = y1 * x1 - z1 * z1;
  93556. y2 = -z1 * y1 - x1 * x1;
  93557. z2 = x1 * z1 + y1 * y1;
  93558. d = 1 / OIMO.sqrt(x2 * x2 + y2 * y2 + z2 * z2);
  93559. this.s = 0;
  93560. this.x = x2 * d;
  93561. this.y = y2 * d;
  93562. this.z = z2 * d;
  93563. return this;
  93564. }
  93565. var cx = y1 * z2 - z1 * y2;
  93566. var cy = z1 * x2 - x1 * z2;
  93567. var cz = x1 * y2 - y1 * x2;
  93568. this.s = OIMO.sqrt((1 + d) * 0.5);
  93569. d = 0.5 / this.s;
  93570. this.x = cx * d;
  93571. this.y = cy * d;
  93572. this.z = cz * d;
  93573. return this;
  93574. },
  93575. normalize: function (q) {
  93576. var len = OIMO.sqrt(q.s * q.s + q.x * q.x + q.y * q.y + q.z * q.z);
  93577. if (len > 0) { len = 1 / len; }
  93578. this.s = q.s * len;
  93579. this.x = q.x * len;
  93580. this.y = q.y * len;
  93581. this.z = q.z * len;
  93582. return this;
  93583. },
  93584. invert: function (q) {
  93585. this.s = q.s;
  93586. this.x = -q.x;
  93587. this.y = -q.y;
  93588. this.z = -q.z;
  93589. return this;
  93590. },
  93591. length: function () {
  93592. return OIMO.sqrt(this.s * this.s + this.x * this.x + this.y * this.y + this.z * this.z);
  93593. },
  93594. copy: function (q) {
  93595. this.s = q.s;
  93596. this.x = q.x;
  93597. this.y = q.y;
  93598. this.z = q.z;
  93599. return this;
  93600. },
  93601. testDiff: function (q) {
  93602. if (this.s !== q.s || this.x !== q.x || this.y !== q.y || this.z !== q.z) return true;
  93603. else return false;
  93604. },
  93605. clone: function (q) {
  93606. return new OIMO.Quat(this.s, this.x, this.y, this.z);
  93607. },
  93608. toString: function () {
  93609. return "Quat[" + this.s.toFixed(4) + ", (" + this.x.toFixed(4) + ", " + this.y.toFixed(4) + ", " + this.z.toFixed(4) + ")]";
  93610. }
  93611. }
  93612. // for three easy export
  93613. OIMO.Quaternion = function (x, y, z, w) {
  93614. this.x = x || 0;
  93615. this.y = y || 0;
  93616. this.z = z || 0;
  93617. this.w = (w !== undefined) ? w : 1;
  93618. };
  93619. OIMO.Quaternion.prototype = {
  93620. constructor: OIMO.Quaternion,
  93621. setFromRotationMatrix: function (m) {
  93622. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  93623. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  93624. var te = m.elements,
  93625. m11 = te[0], m12 = te[1], m13 = te[2],
  93626. m21 = te[3], m22 = te[4], m23 = te[5],
  93627. m31 = te[6], m32 = te[7], m33 = te[8],
  93628. trace = m11 + m22 + m33,
  93629. s;
  93630. if (trace > 0) {
  93631. s = 0.5 / OIMO.sqrt(trace + 1.0);
  93632. this.w = 0.25 / s;
  93633. this.x = (m32 - m23) * s;
  93634. this.y = (m13 - m31) * s;
  93635. this.z = (m21 - m12) * s;
  93636. } else if (m11 > m22 && m11 > m33) {
  93637. s = 2.0 * OIMO.sqrt(1.0 + m11 - m22 - m33);
  93638. this.w = (m32 - m23) / s;
  93639. this.x = 0.25 * s;
  93640. this.y = (m12 + m21) / s;
  93641. this.z = (m13 + m31) / s;
  93642. } else if (m22 > m33) {
  93643. s = 2.0 * OIMO.sqrt(1.0 + m22 - m11 - m33);
  93644. this.w = (m13 - m31) / s;
  93645. this.x = (m12 + m21) / s;
  93646. this.y = 0.25 * s;
  93647. this.z = (m23 + m32) / s;
  93648. } else {
  93649. s = 2.0 * OIMO.sqrt(1.0 + m33 - m11 - m22);
  93650. this.w = (m21 - m12) / s;
  93651. this.x = (m13 + m31) / s;
  93652. this.y = (m23 + m32) / s;
  93653. this.z = 0.25 * s;
  93654. }
  93655. //this.onChangeCallback();
  93656. return this;
  93657. }
  93658. }
  93659. OIMO.Vec3 = function (x, y, z) {
  93660. this.x = x || 0;
  93661. this.y = y || 0;
  93662. this.z = z || 0;
  93663. };
  93664. OIMO.Vec3.prototype = {
  93665. constructor: OIMO.Vec3,
  93666. init: function (x, y, z) {
  93667. this.x = x || 0;
  93668. this.y = y || 0;
  93669. this.z = z || 0;
  93670. return this;
  93671. },
  93672. set: function (x, y, z) {
  93673. this.x = x;
  93674. this.y = y;
  93675. this.z = z;
  93676. return this;
  93677. },
  93678. add: function (v1, v2) {
  93679. this.x = v1.x + v2.x;
  93680. this.y = v1.y + v2.y;
  93681. this.z = v1.z + v2.z;
  93682. return this;
  93683. },
  93684. addEqual: function (v) {
  93685. this.x += v.x;
  93686. this.y += v.y;
  93687. this.z += v.z;
  93688. return this;
  93689. },
  93690. addTime: function (v, t) {
  93691. this.x += v.x * t;
  93692. this.y += v.y * t;
  93693. this.z += v.z * t;
  93694. return this;
  93695. },
  93696. sub: function (v1, v2) {
  93697. this.x = v1.x - v2.x;
  93698. this.y = v1.y - v2.y;
  93699. this.z = v1.z - v2.z;
  93700. return this;
  93701. },
  93702. subEqual: function (v) {
  93703. this.x -= v.x;
  93704. this.y -= v.y;
  93705. this.z -= v.z;
  93706. return this;
  93707. },
  93708. addScale: function (v, s) {
  93709. this.x += v.x * s;
  93710. this.y += v.y * s;
  93711. this.z += v.z * s;
  93712. return this;
  93713. },
  93714. scale: function (v, s) {
  93715. this.x = v.x * s;
  93716. this.y = v.y * s;
  93717. this.z = v.z * s;
  93718. return this;
  93719. },
  93720. scaleEqual: function (s) {
  93721. this.x *= s;
  93722. this.y *= s;
  93723. this.z *= s;
  93724. return this;
  93725. },
  93726. /*dot: function(v){
  93727. return this.x*v.x+this.y*v.y+this.z*v.z;
  93728. },*/
  93729. cross: function (v1, v2) {
  93730. var ax = v1.x, ay = v1.y, az = v1.z,
  93731. bx = v2.x, by = v2.y, bz = v2.z;
  93732. this.x = ay * bz - az * by;
  93733. this.y = az * bx - ax * bz;
  93734. this.z = ax * by - ay * bx;
  93735. return this;
  93736. },
  93737. mul: function (o, v, m) {
  93738. var te = m.elements;
  93739. this.x = o.x + v.x * te[0] + v.y * te[1] + v.z * te[2];
  93740. this.y = o.y + v.x * te[3] + v.y * te[4] + v.z * te[5];
  93741. this.z = o.z + v.x * te[6] + v.y * te[7] + v.z * te[8];
  93742. return this;
  93743. },
  93744. mulMat: function (m, v) {
  93745. var te = m.elements;
  93746. this.x = te[0] * v.x + te[1] * v.y + te[2] * v.z;
  93747. this.y = te[3] * v.x + te[4] * v.y + te[5] * v.z;
  93748. this.z = te[6] * v.x + te[7] * v.y + te[8] * v.z;
  93749. return this;
  93750. },
  93751. normalize: function (v) {
  93752. var x = v.x, y = v.y, z = v.z;
  93753. var l = x * x + y * y + z * z;
  93754. if (l > 0) {
  93755. l = 1 / OIMO.sqrt(l);
  93756. this.x = x * l;
  93757. this.y = y * l;
  93758. this.z = z * l;
  93759. }
  93760. return this;
  93761. },
  93762. /*norm: function(){
  93763. var x = this.x, y = this.y, z = this.z;
  93764. var l = x*x + y*y + z*z;
  93765. if (l > 0) {
  93766. l = 1 / OIMO.sqrt(l);
  93767. this.x = x*l;
  93768. this.y = y*l;
  93769. this.z = z*l;
  93770. }
  93771. return this;
  93772. },*/
  93773. invert: function (v) {
  93774. this.x = -v.x;
  93775. this.y = -v.y;
  93776. this.z = -v.z;
  93777. return this;
  93778. },
  93779. /*length: function(){
  93780. var x = this.x, y = this.y, z = this.z;
  93781. return OIMO.sqrt(x*x + y*y + z*z);
  93782. },*/
  93783. negate: function () {
  93784. this.x = -this.x;
  93785. this.y = -this.y;
  93786. this.z = -this.z;
  93787. return this;
  93788. },
  93789. dot: function (v) {
  93790. return this.x * v.x + this.y * v.y + this.z * v.z;
  93791. },
  93792. lengthSq: function () {
  93793. return this.x * this.x + this.y * this.y + this.z * this.z;
  93794. },
  93795. length: function () {
  93796. return OIMO.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  93797. },
  93798. /*len: function(){
  93799. var x = this.x, y = this.y, z = this.z;
  93800. return x*x + y*y + z*z;
  93801. },*/
  93802. copy: function (v) {
  93803. this.x = v.x;
  93804. this.y = v.y;
  93805. this.z = v.z;
  93806. return this;
  93807. },
  93808. applyQuaternion: function (q) {
  93809. var x = this.x;
  93810. var y = this.y;
  93811. var z = this.z;
  93812. var qx = q.x;
  93813. var qy = q.y;
  93814. var qz = q.z;
  93815. var qs = q.s;
  93816. // calculate quat * vector
  93817. var ix = qs * x + qy * z - qz * y;
  93818. var iy = qs * y + qz * x - qx * z;
  93819. var iz = qs * z + qx * y - qy * x;
  93820. var iw = -qx * x - qy * y - qz * z;
  93821. // calculate result * inverse quat
  93822. this.x = ix * qs + iw * -qx + iy * -qz - iz * -qy;
  93823. this.y = iy * qs + iw * -qy + iz * -qx - ix * -qz;
  93824. this.z = iz * qs + iw * -qz + ix * -qy - iy * -qx;
  93825. return this;
  93826. },
  93827. testZero: function () {
  93828. if (this.x !== 0 || this.y !== 0 || this.z !== 0) return true;
  93829. else return false;
  93830. },
  93831. testDiff: function (v) {
  93832. return ((v.x !== this.x) || (v.y !== this.y) || (v.z !== this.z));
  93833. //if(this.x!==v.x || this.y!==v.y || this.z!==v.z) return true;
  93834. //else return false;
  93835. },
  93836. equals: function (v) {
  93837. return ((v.x === this.x) && (v.y === this.y) && (v.z === this.z));
  93838. },
  93839. clone: function () {
  93840. return new this.constructor(this.x, this.y, this.z);
  93841. },
  93842. toString: function () {
  93843. return "Vec3[" + this.x.toFixed(4) + ", " + this.y.toFixed(4) + ", " + this.z.toFixed(4) + "]";
  93844. },
  93845. multiplyScalar: function (scalar) {
  93846. if (isFinite(scalar)) {
  93847. this.x *= scalar;
  93848. this.y *= scalar;
  93849. this.z *= scalar;
  93850. } else {
  93851. this.x = 0;
  93852. this.y = 0;
  93853. this.z = 0;
  93854. }
  93855. return this;
  93856. },
  93857. divideScalar: function (scalar) {
  93858. return this.multiplyScalar(1 / scalar);
  93859. },
  93860. // TODO rename to normalize
  93861. norm: function () {
  93862. return this.divideScalar(this.length());
  93863. },
  93864. }
  93865. OIMO.Euler = function (x, y, z, order) {
  93866. this._x = x || 0;
  93867. this._y = y || 0;
  93868. this._z = z || 0;
  93869. this._order = order || OIMO.Euler.DefaultOrder;
  93870. };
  93871. OIMO.Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  93872. OIMO.Euler.DefaultOrder = 'XYZ';
  93873. OIMO.clamp = function (x, a, b) {
  93874. return (x < a) ? a : ((x > b) ? b : x);
  93875. }
  93876. OIMO.Euler.prototype = {
  93877. constructor: OIMO.Euler,
  93878. _x: 0, _y: 0, _z: 0, _order: OIMO.Euler.DefaultOrder,
  93879. get x() {
  93880. return this._x;
  93881. },
  93882. set x(value) {
  93883. this._x = value;
  93884. this.onChangeCallback();
  93885. },
  93886. get y() {
  93887. return this._y;
  93888. },
  93889. set y(value) {
  93890. this._y = value;
  93891. this.onChangeCallback();
  93892. },
  93893. get z() {
  93894. return this._z;
  93895. },
  93896. set z(value) {
  93897. this._z = value;
  93898. this.onChangeCallback();
  93899. },
  93900. get order() {
  93901. return this._order;
  93902. },
  93903. set order(value) {
  93904. this._order = value;
  93905. this.onChangeCallback();
  93906. },
  93907. set: function (x, y, z, order) {
  93908. this._x = x;
  93909. this._y = y;
  93910. this._z = z;
  93911. this._order = order || this._order;
  93912. this.onChangeCallback();
  93913. return this;
  93914. },
  93915. copy: function (euler) {
  93916. this._x = euler._x;
  93917. this._y = euler._y;
  93918. this._z = euler._z;
  93919. this._order = euler._order;
  93920. this.onChangeCallback();
  93921. return this;
  93922. },
  93923. setFromRotationMatrix: function (m, order) {
  93924. var clamp = OIMO.clamp;
  93925. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  93926. var te = m.elements;
  93927. /*var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  93928. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  93929. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];*/
  93930. var m11 = te[0], m12 = te[1], m13 = te[2],
  93931. m21 = te[3], m22 = te[4], m23 = te[5],
  93932. m31 = te[6], m32 = te[7], m33 = te[8];
  93933. order = order || this._order;
  93934. if (order === 'XYZ') {
  93935. this._y = OIMO.asin(clamp(m13, -1, 1));
  93936. if (OIMO.abs(m13) < 0.99999) {
  93937. this._x = OIMO.atan2(-m23, m33);
  93938. this._z = OIMO.atan2(-m12, m11);
  93939. } else {
  93940. this._x = OIMO.atan2(m32, m22);
  93941. this._z = 0;
  93942. }
  93943. } else if (order === 'YXZ') {
  93944. this._x = OIMO.asin(-clamp(m23, -1, 1));
  93945. if (OIMO.abs(m23) < 0.99999) {
  93946. this._y = OIMO.atan2(m13, m33);
  93947. this._z = OIMO.atan2(m21, m22);
  93948. } else {
  93949. this._y = OIMO.atan2(-m31, m11);
  93950. this._z = 0;
  93951. }
  93952. } else if (order === 'ZXY') {
  93953. this._x = OIMO.asin(clamp(m32, -1, 1));
  93954. if (OIMO.abs(m32) < 0.99999) {
  93955. this._y = OIMO.atan2(-m31, m33);
  93956. this._z = OIMO.atan2(-m12, m22);
  93957. } else {
  93958. this._y = 0;
  93959. this._z = OIMO.atan2(m21, m11);
  93960. }
  93961. } else if (order === 'ZYX') {
  93962. this._y = OIMO.asin(-clamp(m31, -1, 1));
  93963. if (OIMO.abs(m31) < 0.99999) {
  93964. this._x = OIMO.atan2(m32, m33);
  93965. this._z = OIMO.atan2(m21, m11);
  93966. } else {
  93967. this._x = 0;
  93968. this._z = OIMO.atan2(-m12, m22);
  93969. }
  93970. } else if (order === 'YZX') {
  93971. this._z = OIMO.asin(clamp(m21, -1, 1));
  93972. if (OIMO.abs(m21) < 0.99999) {
  93973. this._x = OIMO.atan2(-m23, m22);
  93974. this._y = OIMO.atan2(-m31, m11);
  93975. } else {
  93976. this._x = 0;
  93977. this._y = OIMO.atan2(m13, m33);
  93978. }
  93979. } else if (order === 'XZY') {
  93980. this._z = OIMO.asin(-clamp(m12, -1, 1));
  93981. if (OIMO.abs(m12) < 0.99999) {
  93982. this._x = OIMO.atan2(m32, m22);
  93983. this._y = OIMO.atan2(m13, m11);
  93984. } else {
  93985. this._x = OIMO.atan2(-m23, m33);
  93986. this._y = 0;
  93987. }
  93988. } else {
  93989. console.warn('THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order)
  93990. }
  93991. this._order = order;
  93992. this.onChangeCallback();
  93993. return this;
  93994. },
  93995. setFromQuaternion: function (q, order, update) {
  93996. var clamp = OIMO.clamp;
  93997. // q is assumed to be normalized
  93998. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  93999. var sqx = q.x * q.x;
  94000. var sqy = q.y * q.y;
  94001. var sqz = q.z * q.z;
  94002. var sqw = q.s * q.s;
  94003. order = order || this._order;
  94004. if (order === 'XYZ') {
  94005. this._x = OIMO.atan2(2 * (q.x * q.s - q.y * q.z), (sqw - sqx - sqy + sqz));
  94006. this._y = OIMO.asin(clamp(2 * (q.x * q.z + q.y * q.s), -1, 1));
  94007. this._z = OIMO.atan2(2 * (q.z * q.s - q.x * q.y), (sqw + sqx - sqy - sqz));
  94008. } else if (order === 'YXZ') {
  94009. this._x = OIMO.asin(clamp(2 * (q.x * q.s - q.y * q.z), -1, 1));
  94010. this._y = OIMO.atan2(2 * (q.x * q.z + q.y * q.s), (sqw - sqx - sqy + sqz));
  94011. this._z = OIMO.atan2(2 * (q.x * q.y + q.z * q.s), (sqw - sqx + sqy - sqz));
  94012. } else if (order === 'ZXY') {
  94013. this._x = OIMO.asin(clamp(2 * (q.x * q.s + q.y * q.z), -1, 1));
  94014. this._y = OIMO.atan2(2 * (q.y * q.s - q.z * q.x), (sqw - sqx - sqy + sqz));
  94015. this._z = OIMO.atan2(2 * (q.z * q.s - q.x * q.y), (sqw - sqx + sqy - sqz));
  94016. } else if (order === 'ZYX') {
  94017. this._x = OIMO.atan2(2 * (q.x * q.s + q.z * q.y), (sqw - sqx - sqy + sqz));
  94018. this._y = OIMO.asin(clamp(2 * (q.y * q.s - q.x * q.z), -1, 1));
  94019. this._z = OIMO.atan2(2 * (q.x * q.y + q.z * q.s), (sqw + sqx - sqy - sqz));
  94020. } else if (order === 'YZX') {
  94021. this._x = OIMO.atan2(2 * (q.x * q.s - q.z * q.y), (sqw - sqx + sqy - sqz));
  94022. this._y = OIMO.atan2(2 * (q.y * q.s - q.x * q.z), (sqw + sqx - sqy - sqz));
  94023. this._z = OIMO.asin(clamp(2 * (q.x * q.y + q.z * q.s), -1, 1));
  94024. } else if (order === 'XZY') {
  94025. this._x = OIMO.atan2(2 * (q.x * q.s + q.y * q.z), (sqw - sqx + sqy - sqz));
  94026. this._y = OIMO.atan2(2 * (q.x * q.z + q.y * q.s), (sqw + sqx - sqy - sqz));
  94027. this._z = OIMO.asin(clamp(2 * (q.z * q.s - q.x * q.y), -1, 1));
  94028. } else {
  94029. console.warn('OIMO.Euler: .setFromQuaternion() given unsupported order: ' + order)
  94030. }
  94031. this._order = order;
  94032. if (update !== false) this.onChangeCallback();
  94033. return this;
  94034. },
  94035. reorder: function () {
  94036. // WARNING: this discards revolution information -bhouston
  94037. var q = new OIMO.Quat();
  94038. return function (newOrder) {
  94039. q.setFromEuler(this);
  94040. this.setFromQuaternion(q, newOrder);
  94041. };
  94042. }(),
  94043. equals: function (euler) {
  94044. return (euler._x === this._x) && (euler._y === this._y) && (euler._z === this._z) && (euler._order === this._order);
  94045. },
  94046. fromArray: function (array) {
  94047. this._x = array[0];
  94048. this._y = array[1];
  94049. this._z = array[2];
  94050. if (array[3] !== undefined) this._order = array[3];
  94051. this.onChangeCallback();
  94052. return this;
  94053. },
  94054. toArray: function () {
  94055. return [this._x, this._y, this._z, this._order];
  94056. },
  94057. onChange: function (callback) {
  94058. this.onChangeCallback = callback;
  94059. return this;
  94060. },
  94061. onChangeCallback: function () { },
  94062. clone: function () {
  94063. return new OIMO.Euler(this._x, this._y, this._z, this._order);
  94064. }
  94065. };
  94066. OIMO.EulerToAxis = function (ox, oy, oz) {// angles in radians
  94067. var c1 = OIMO.cos(oy * 0.5);//heading
  94068. var s1 = OIMO.sin(oy * 0.5);
  94069. var c2 = OIMO.cos(oz * 0.5);//altitude
  94070. var s2 = OIMO.sin(oz * 0.5);
  94071. var c3 = OIMO.cos(ox * 0.5);//bank
  94072. var s3 = OIMO.sin(ox * 0.5);
  94073. var c1c2 = c1 * c2;
  94074. var s1s2 = s1 * s2;
  94075. var w = c1c2 * c3 - s1s2 * s3;
  94076. var x = c1c2 * s3 + s1s2 * c3;
  94077. var y = s1 * c2 * c3 + c1 * s2 * s3;
  94078. var z = c1 * s2 * c3 - s1 * c2 * s3;
  94079. var angle = 2 * OIMO.acos(w);
  94080. var norm = x * x + y * y + z * z;
  94081. if (norm < 0.001) {
  94082. x = 1;
  94083. y = z = 0;
  94084. } else {
  94085. norm = OIMO.sqrt(norm);
  94086. x /= norm;
  94087. y /= norm;
  94088. z /= norm;
  94089. }
  94090. return [angle, x, y, z];
  94091. }
  94092. OIMO.EulerToMatrix = function (ox, oy, oz) {// angles in radians
  94093. var ch = OIMO.cos(oy);//heading
  94094. var sh = OIMO.sin(oy);
  94095. var ca = OIMO.cos(oz);//altitude
  94096. var sa = OIMO.sin(oz);
  94097. var cb = OIMO.cos(ox);//bank
  94098. var sb = OIMO.sin(ox);
  94099. var mtx = new OIMO.Mat33();
  94100. var te = mtx.elements;
  94101. te[0] = ch * ca;
  94102. te[1] = sh * sb - ch * sa * cb;
  94103. te[2] = ch * sa * sb + sh * cb;
  94104. te[3] = sa;
  94105. te[4] = ca * cb;
  94106. te[5] = -ca * sb;
  94107. te[6] = -sh * ca;
  94108. te[7] = sh * sa * cb + ch * sb;
  94109. te[8] = -sh * sa * sb + ch * cb;
  94110. return mtx;
  94111. }
  94112. OIMO.MatrixToEuler = function (mtx) {// angles in radians
  94113. var te = mtx.elements;
  94114. var x, y, z;
  94115. if (te[3] > 0.998) { // singularity at north pole
  94116. y = OIMO.atan2(te[2], te[8]);
  94117. z = OIMO.PI / 2;
  94118. x = 0;
  94119. } else if (te[3] < -0.998) { // singularity at south pole
  94120. y = OIMO.atan2(te[2], te[8]);
  94121. z = -OIMO.PI / 2;
  94122. x = 0;
  94123. } else {
  94124. y = OIMO.atan2(-te[6], te[0]);
  94125. x = OIMO.atan2(-te[5], te[4]);
  94126. z = OIMO.asin(te[3]);
  94127. }
  94128. return [x, y, z];
  94129. }
  94130. OIMO.unwrapDegrees = function (r) {
  94131. r = r % 360;
  94132. if (r > 180) r -= 360;
  94133. if (r < -180) r += 360;
  94134. return r;
  94135. }
  94136. OIMO.unwrapRadian = function (r) {
  94137. r = r % OIMO.TwoPI;
  94138. if (r > OIMO.PI) r -= OIMO.TwoPI;
  94139. if (r < -OIMO.PI) r += OIMO.TwoPI;
  94140. return r;
  94141. }
  94142. OIMO.Distance3d = function (p1, p2) {
  94143. var xd = p2[0] - p1[0];
  94144. var yd = p2[1] - p1[1];
  94145. var zd = p2[2] - p1[2];
  94146. return OIMO.sqrt(xd * xd + yd * yd + zd * zd);
  94147. }
  94148. /**
  94149. * The base class of all type of the constraints.
  94150. * @author saharan
  94151. */
  94152. OIMO.Constraint = function () {
  94153. // The parent world of the constraint.
  94154. this.parent = null;
  94155. // The first body of the constraint.
  94156. this.body1 = null;
  94157. // The second body of the constraint.
  94158. this.body2 = null;
  94159. // Internal
  94160. this.addedToIsland = false;
  94161. }
  94162. OIMO.Constraint.prototype = {
  94163. constructor: OIMO.Constraint,
  94164. /**
  94165. * Prepare for solving the constraint.
  94166. * @param timeStep
  94167. * @param invTimeStep
  94168. */
  94169. preSolve: function (timeStep, invTimeStep) {
  94170. OIMO.Error("Constraint", "Inheritance error.");
  94171. },
  94172. /**
  94173. * Solve the constraint.
  94174. * This is usually called iteratively.
  94175. */
  94176. solve: function () {
  94177. OIMO.Error("Constraint", "Inheritance error.");
  94178. },
  94179. /**
  94180. * Do the post-processing.
  94181. */
  94182. postSolve: function () {
  94183. OIMO.Error("Constraint", "Inheritance error.");
  94184. }
  94185. }
  94186. /**
  94187. * Joints are used to constrain the motion between two rigid bodies.
  94188. * @author saharan
  94189. * @author lo-th
  94190. */
  94191. OIMO.Joint = function (config) {
  94192. OIMO.Constraint.call(this);
  94193. // joint name
  94194. this.name = "";
  94195. // The type of the joint.
  94196. this.type = OIMO.JOINT_NULL;
  94197. // The previous joint in the world.
  94198. this.prev = null;
  94199. // The next joint in the world.
  94200. this.next = null;
  94201. this.body1 = config.body1;
  94202. this.body2 = config.body2;
  94203. // The anchor point on the first rigid body in local coordinate system.
  94204. this.localAnchorPoint1 = new OIMO.Vec3().copy(config.localAnchorPoint1);
  94205. // The anchor point on the second rigid body in local coordinate system.
  94206. this.localAnchorPoint2 = new OIMO.Vec3().copy(config.localAnchorPoint2);
  94207. // The anchor point on the first rigid body in world coordinate system relative to the body's origin.
  94208. this.relativeAnchorPoint1 = new OIMO.Vec3();
  94209. // The anchor point on the second rigid body in world coordinate system relative to the body's origin.
  94210. this.relativeAnchorPoint2 = new OIMO.Vec3();
  94211. // The anchor point on the first rigid body in world coordinate system.
  94212. this.anchorPoint1 = new OIMO.Vec3();
  94213. // The anchor point on the second rigid body in world coordinate system.
  94214. this.anchorPoint2 = new OIMO.Vec3();
  94215. // Whether allow collision between connected rigid bodies or not.
  94216. this.allowCollision = config.allowCollision;
  94217. this.b1Link = new OIMO.JointLink(this);
  94218. this.b2Link = new OIMO.JointLink(this);
  94219. this.matrix = new OIMO.Mat44();
  94220. };
  94221. OIMO.Joint.prototype = Object.create(OIMO.Constraint.prototype);
  94222. OIMO.Joint.prototype.constructor = OIMO.Joint;
  94223. // Update all the anchor points.
  94224. OIMO.Joint.prototype.updateAnchorPoints = function () {
  94225. this.relativeAnchorPoint1.mulMat(this.body1.rotation, this.localAnchorPoint1);
  94226. this.relativeAnchorPoint2.mulMat(this.body2.rotation, this.localAnchorPoint2);
  94227. this.anchorPoint1.add(this.relativeAnchorPoint1, this.body1.position);
  94228. this.anchorPoint2.add(this.relativeAnchorPoint2, this.body2.position);
  94229. };
  94230. // Attach the joint from the bodies.
  94231. OIMO.Joint.prototype.attach = function () {
  94232. this.b1Link.body = this.body2;
  94233. this.b2Link.body = this.body1;
  94234. if (this.body1.jointLink != null) (this.b1Link.next = this.body1.jointLink).prev = this.b1Link;
  94235. else this.b1Link.next = null;
  94236. this.body1.jointLink = this.b1Link;
  94237. this.body1.numJoints++;
  94238. if (this.body2.jointLink != null) (this.b2Link.next = this.body2.jointLink).prev = this.b2Link;
  94239. else this.b2Link.next = null;
  94240. this.body2.jointLink = this.b2Link;
  94241. this.body2.numJoints++;
  94242. };
  94243. // Detach the joint from the bodies.
  94244. OIMO.Joint.prototype.detach = function () {
  94245. var prev = this.b1Link.prev;
  94246. var next = this.b1Link.next;
  94247. if (prev != null) prev.next = next;
  94248. if (next != null) next.prev = prev;
  94249. if (this.body1.jointLink == this.b1Link) this.body1.jointLink = next;
  94250. this.b1Link.prev = null;
  94251. this.b1Link.next = null;
  94252. this.b1Link.body = null;
  94253. this.body1.numJoints--;
  94254. prev = this.b2Link.prev;
  94255. next = this.b2Link.next;
  94256. if (prev != null) prev.next = next;
  94257. if (next != null) next.prev = prev;
  94258. if (this.body2.jointLink == this.b2Link) this.body2.jointLink = next;
  94259. this.b2Link.prev = null;
  94260. this.b2Link.next = null;
  94261. this.b2Link.body = null;
  94262. this.body2.numJoints--;
  94263. this.b1Link.body = null;
  94264. this.b2Link.body = null;
  94265. };
  94266. // Awake the bodies.
  94267. OIMO.Joint.prototype.awake = function () {
  94268. this.body1.awake();
  94269. this.body2.awake();
  94270. };
  94271. // calculation function
  94272. OIMO.Joint.prototype.preSolve = function (timeStep, invTimeStep) {
  94273. };
  94274. OIMO.Joint.prototype.solve = function () {
  94275. };
  94276. OIMO.Joint.prototype.postSolve = function () {
  94277. };
  94278. // Delete process
  94279. OIMO.Joint.prototype.remove = function () {
  94280. this.dispose();
  94281. };
  94282. OIMO.Joint.prototype.dispose = function () {
  94283. this.parent.removeJoint(this);
  94284. };
  94285. // Three js add
  94286. OIMO.Joint.prototype.getPosition = function () {
  94287. var p1 = new OIMO.Vec3().scale(this.anchorPoint1, OIMO.WORLD_SCALE);
  94288. var p2 = new OIMO.Vec3().scale(this.anchorPoint2, OIMO.WORLD_SCALE);
  94289. return [p1, p2];
  94290. };
  94291. OIMO.Joint.prototype.getMatrix = function () {
  94292. var m = this.matrix.elements;
  94293. var p1 = this.anchorPoint1;
  94294. var p2 = this.anchorPoint2;
  94295. m[0] = p1.x * OIMO.WORLD_SCALE;
  94296. m[1] = p1.y * OIMO.WORLD_SCALE;
  94297. m[2] = p1.z * OIMO.WORLD_SCALE;
  94298. m[3] = 0;
  94299. m[4] = p2.x * OIMO.WORLD_SCALE;
  94300. m[5] = p2.y * OIMO.WORLD_SCALE;
  94301. m[6] = p2.z * OIMO.WORLD_SCALE;
  94302. m[7] = 0;
  94303. return m;
  94304. };
  94305. /**
  94306. * A joint configuration holds all configuration data for constructing a joint.
  94307. * Joint configurations can be reused safely.
  94308. * @author saharan
  94309. */
  94310. OIMO.JointConfig = function () {
  94311. // The first rigid body of the joint.
  94312. this.body1 = null;
  94313. // The second rigid body of the joint.
  94314. this.body2 = null;
  94315. // The anchor point on the first rigid body in local coordinate system.
  94316. this.localAnchorPoint1 = new OIMO.Vec3();
  94317. // The anchor point on the second rigid body in local coordinate system.
  94318. this.localAnchorPoint2 = new OIMO.Vec3();
  94319. // The axis in the first body's coordinate system.
  94320. // his property is available in some joints.
  94321. this.localAxis1 = new OIMO.Vec3();
  94322. // The axis in the second body's coordinate system.
  94323. // This property is available in some joints.
  94324. this.localAxis2 = new OIMO.Vec3();
  94325. // Whether allow collision between connected rigid bodies or not.
  94326. this.allowCollision = false;
  94327. };
  94328. /**
  94329. * A link list of joints.
  94330. * @author saharan
  94331. */
  94332. OIMO.JointLink = function (joint) {
  94333. // The previous joint link.
  94334. this.prev = null;
  94335. // The next joint link.
  94336. this.next = null;
  94337. // The other rigid body connected to the joint.
  94338. this.body = null;
  94339. // The joint of the link.
  94340. this.joint = joint;
  94341. };
  94342. /**
  94343. * An information of limit and motor.
  94344. * @author saharan
  94345. */
  94346. OIMO.LimitMotor = function (axis, fixed) {
  94347. fixed = fixed || false;
  94348. // The axis of the constraint.
  94349. this.axis = axis;
  94350. // The current angle for rotational constraints.
  94351. this.angle = 0;
  94352. // The lower limit. Set lower > upper to disable
  94353. this.lowerLimit = fixed ? 0 : 1;
  94354. //if(fixed)this.lowerLimit = 0;
  94355. //else this.lowerLimit = 1;
  94356. // The upper limit. Set lower > upper to disable.
  94357. this.upperLimit = 0;
  94358. // The target motor speed.
  94359. this.motorSpeed = 0;
  94360. // The maximum motor force or torque. Set 0 to disable.
  94361. this.maxMotorForce = 0;
  94362. // The frequency of the spring. Set 0 to disable.
  94363. this.frequency = 0;
  94364. // The damping ratio of the spring. Set 0 for no damping, 1 for critical damping.
  94365. this.dampingRatio = 0;
  94366. };
  94367. OIMO.LimitMotor.prototype = {
  94368. constructor: OIMO.LimitMotor,
  94369. /**
  94370. * Set limit data into this constraint.
  94371. * @param lowerLimit
  94372. * @param upperLimit
  94373. */
  94374. setLimit: function (lowerLimit, upperLimit) {
  94375. this.lowerLimit = lowerLimit;
  94376. this.upperLimit = upperLimit;
  94377. },
  94378. /**
  94379. * Set motor data into this constraint.
  94380. * @param motorSpeed
  94381. * @param maxMotorForce
  94382. */
  94383. setMotor: function (motorSpeed, maxMotorForce) {
  94384. this.motorSpeed = motorSpeed;
  94385. this.maxMotorForce = maxMotorForce;
  94386. },
  94387. /**
  94388. * Set spring data into this constraint.
  94389. * @param frequency
  94390. * @param dampingRatio
  94391. */
  94392. setSpring: function (frequency, dampingRatio) {
  94393. this.frequency = frequency;
  94394. this.dampingRatio = dampingRatio;
  94395. }
  94396. };
  94397. /**
  94398. * A ball-and-socket joint limits relative translation on two anchor points on rigid bodies.
  94399. * @author saharan
  94400. * @author lo-th
  94401. */
  94402. OIMO.BallAndSocketJoint = function (config) {
  94403. OIMO.Joint.call(this, config);
  94404. this.type = OIMO.JOINT_BALL_AND_SOCKET;
  94405. this.lc = new OIMO.LinearConstraint(this);
  94406. };
  94407. OIMO.BallAndSocketJoint.prototype = Object.create(OIMO.Joint.prototype);
  94408. OIMO.BallAndSocketJoint.prototype.constructor = OIMO.BallAndSocketJoint;
  94409. OIMO.BallAndSocketJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  94410. this.updateAnchorPoints();
  94411. this.lc.preSolve(timeStep, invTimeStep);
  94412. };
  94413. OIMO.BallAndSocketJoint.prototype.solve = function () {
  94414. this.lc.solve();
  94415. };
  94416. OIMO.BallAndSocketJoint.prototype.postSolve = function () {
  94417. };
  94418. /**
  94419. * A distance joint limits the distance between two anchor points on rigid bodies.
  94420. * @author saharan
  94421. * @author lo-th
  94422. */
  94423. OIMO.DistanceJoint = function (config, minDistance, maxDistance) {
  94424. OIMO.Joint.call(this, config);
  94425. this.type = OIMO.JOINT_DISTANCE;
  94426. this.normal = new OIMO.Vec3();
  94427. this.nr = new OIMO.Vec3();
  94428. // The limit and motor information of the joint.
  94429. this.limitMotor = new OIMO.LimitMotor(this.normal, true);
  94430. this.limitMotor.lowerLimit = minDistance;
  94431. this.limitMotor.upperLimit = maxDistance;
  94432. this.t = new OIMO.TranslationalConstraint(this, this.limitMotor);
  94433. };
  94434. OIMO.DistanceJoint.prototype = Object.create(OIMO.Joint.prototype);
  94435. OIMO.DistanceJoint.prototype.constructor = OIMO.DistanceJoint;
  94436. OIMO.DistanceJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  94437. this.updateAnchorPoints();
  94438. //var nr = this.nr;
  94439. this.nr.sub(this.anchorPoint2, this.anchorPoint1);
  94440. //var len = OIMO.sqrt( nr.x*nr.x + nr.y*nr.y + nr.z*nr.z );
  94441. //if(len>0) len = 1/len;
  94442. //this.normal.scale( nr, len );
  94443. this.normal.normalize(this.nr);
  94444. this.t.preSolve(timeStep, invTimeStep);
  94445. };
  94446. OIMO.DistanceJoint.prototype.solve = function () {
  94447. this.t.solve();
  94448. };
  94449. OIMO.DistanceJoint.prototype.postSolve = function () {
  94450. };
  94451. /**
  94452. * A hinge joint allows only for relative rotation of rigid bodies along the axis.
  94453. * @author saharan
  94454. * @author lo-th
  94455. */
  94456. OIMO.HingeJoint = function (config, lowerAngleLimit, upperAngleLimit) {
  94457. OIMO.Joint.call(this, config);
  94458. this.type = OIMO.JOINT_HINGE;
  94459. // The axis in the first body's coordinate system.
  94460. this.localAxis1 = config.localAxis1.clone().norm();
  94461. // The axis in the second body's coordinate system.
  94462. this.localAxis2 = config.localAxis2.clone().norm();
  94463. // make angle axis 1
  94464. this.localAngle1 = new OIMO.Vec3(
  94465. this.localAxis1.y * this.localAxis1.x - this.localAxis1.z * this.localAxis1.z,
  94466. -this.localAxis1.z * this.localAxis1.y - this.localAxis1.x * this.localAxis1.x,
  94467. this.localAxis1.x * this.localAxis1.z + this.localAxis1.y * this.localAxis1.y
  94468. ).norm();
  94469. // make angle axis 2
  94470. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  94471. this.localAngle2 = new OIMO.Vec3().mulMat(arc, this.localAngle1);
  94472. this.nor = new OIMO.Vec3();
  94473. this.tan = new OIMO.Vec3();
  94474. this.bin = new OIMO.Vec3();
  94475. this.ax1 = new OIMO.Vec3();
  94476. this.ax2 = new OIMO.Vec3();
  94477. this.an1 = new OIMO.Vec3();
  94478. this.an2 = new OIMO.Vec3();
  94479. // The rotational limit and motor information of the joint.
  94480. this.limitMotor = new OIMO.LimitMotor(this.nor, false);
  94481. this.limitMotor.lowerLimit = lowerAngleLimit;
  94482. this.limitMotor.upperLimit = upperAngleLimit;
  94483. this.lc = new OIMO.LinearConstraint(this);
  94484. this.r3 = new OIMO.Rotational3Constraint(this, this.limitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  94485. };
  94486. OIMO.HingeJoint.prototype = Object.create(OIMO.Joint.prototype);
  94487. OIMO.HingeJoint.prototype.constructor = OIMO.HingeJoint;
  94488. OIMO.HingeJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  94489. var tmp1X, tmp1Y, tmp1Z, limite;//, nx, ny, nz, tx, ty, tz, bx, by, bz;
  94490. this.updateAnchorPoints();
  94491. this.ax1.mulMat(this.body1.rotation, this.localAxis1);
  94492. this.ax2.mulMat(this.body2.rotation, this.localAxis2);
  94493. this.an1.mulMat(this.body1.rotation, this.localAngle1);
  94494. this.an2.mulMat(this.body2.rotation, this.localAngle2);
  94495. this.nor.set(
  94496. this.ax1.x * this.body2.inverseMass + this.ax2.x * this.body1.inverseMass,
  94497. this.ax1.y * this.body2.inverseMass + this.ax2.y * this.body1.inverseMass,
  94498. this.ax1.z * this.body2.inverseMass + this.ax2.z * this.body1.inverseMass
  94499. ).norm();
  94500. this.tan.set(
  94501. this.nor.y * this.nor.x - this.nor.z * this.nor.z,
  94502. -this.nor.z * this.nor.y - this.nor.x * this.nor.x,
  94503. this.nor.x * this.nor.z + this.nor.y * this.nor.y
  94504. ).norm();
  94505. this.bin.set(
  94506. this.nor.y * this.tan.z - this.nor.z * this.tan.y,
  94507. this.nor.z * this.tan.x - this.nor.x * this.tan.z,
  94508. this.nor.x * this.tan.y - this.nor.y * this.tan.x
  94509. );
  94510. // calculate hinge angle
  94511. limite = this.acosClamp(this.an1.x * this.an2.x + this.an1.y * this.an2.y + this.an1.z * this.an2.z)
  94512. if (
  94513. this.nor.x * (this.an1.y * this.an2.z - this.an1.z * this.an2.y) +
  94514. this.nor.y * (this.an1.z * this.an2.x - this.an1.x * this.an2.z) +
  94515. this.nor.z * (this.an1.x * this.an2.y - this.an1.y * this.an2.x) < 0
  94516. ) {
  94517. this.limitMotor.angle = -limite;
  94518. } else {
  94519. this.limitMotor.angle = limite;
  94520. }
  94521. tmp1X = this.ax1.y * this.ax2.z - this.ax1.z * this.ax2.y;
  94522. tmp1Y = this.ax1.z * this.ax2.x - this.ax1.x * this.ax2.z;
  94523. tmp1Z = this.ax1.x * this.ax2.y - this.ax1.y * this.ax2.x;
  94524. this.r3.limitMotor2.angle = this.tan.x * tmp1X + this.tan.y * tmp1Y + this.tan.z * tmp1Z;
  94525. this.r3.limitMotor3.angle = this.bin.x * tmp1X + this.bin.y * tmp1Y + this.bin.z * tmp1Z;
  94526. this.r3.preSolve(timeStep, invTimeStep);
  94527. this.lc.preSolve(timeStep, invTimeStep);
  94528. };
  94529. OIMO.HingeJoint.prototype.solve = function () {
  94530. this.r3.solve();
  94531. this.lc.solve();
  94532. };
  94533. OIMO.HingeJoint.prototype.postSolve = function () {
  94534. };
  94535. OIMO.HingeJoint.prototype.acosClamp = function (cos) {
  94536. if (cos > 1) return 0;
  94537. else if (cos < -1) return OIMO.PI;
  94538. else return OIMO.acos(cos);
  94539. };
  94540. /**
  94541. * A prismatic joint allows only for relative translation of rigid bodies along the axis.
  94542. * @author saharan
  94543. * @author lo-th
  94544. */
  94545. OIMO.PrismaticJoint = function (config, lowerTranslation, upperTranslation) {
  94546. OIMO.Joint.call(this, config);
  94547. this.type = OIMO.JOINT_PRISMATIC;
  94548. // The axis in the first body's coordinate system.
  94549. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  94550. // The axis in the second body's coordinate system.
  94551. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  94552. this.localAxis1X = this.localAxis1.x;
  94553. this.localAxis1Y = this.localAxis1.y;
  94554. this.localAxis1Z = this.localAxis1.z;
  94555. this.localAxis2X = this.localAxis2.x;
  94556. this.localAxis2Y = this.localAxis2.y;
  94557. this.localAxis2Z = this.localAxis2.z;
  94558. this.nor = new OIMO.Vec3();
  94559. this.tan = new OIMO.Vec3();
  94560. this.bin = new OIMO.Vec3();
  94561. this.ac = new OIMO.AngularConstraint(this, new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  94562. // The translational limit and motor information of the joint.
  94563. this.limitMotor = new OIMO.LimitMotor(this.nor, true);
  94564. this.limitMotor.lowerLimit = lowerTranslation;
  94565. this.limitMotor.upperLimit = upperTranslation;
  94566. this.t3 = new OIMO.Translational3Constraint(this, this.limitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  94567. };
  94568. OIMO.PrismaticJoint.prototype = Object.create(OIMO.Joint.prototype);
  94569. OIMO.PrismaticJoint.prototype.constructor = OIMO.PrismaticJoint;
  94570. OIMO.PrismaticJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  94571. var tmpM;
  94572. var tmp1X;
  94573. var tmp1Y;
  94574. var tmp1Z;
  94575. this.updateAnchorPoints();
  94576. tmpM = this.body1.rotation.elements;
  94577. var axis1X = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  94578. var axis1Y = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  94579. var axis1Z = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  94580. tmpM = this.body2.rotation.elements;
  94581. var axis2X = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  94582. var axis2Y = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  94583. var axis2Z = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  94584. var nx = axis1X * this.body2.inverseMass + axis2X * this.body1.inverseMass;
  94585. var ny = axis1Y * this.body2.inverseMass + axis2Y * this.body1.inverseMass;
  94586. var nz = axis1Z * this.body2.inverseMass + axis2Z * this.body1.inverseMass;
  94587. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  94588. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  94589. nx *= tmp1X;
  94590. ny *= tmp1X;
  94591. nz *= tmp1X;
  94592. var tx = ny * nx - nz * nz;
  94593. var ty = -nz * ny - nx * nx;
  94594. var tz = nx * nz + ny * ny;
  94595. tmp1X = 1 / OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  94596. tx *= tmp1X;
  94597. ty *= tmp1X;
  94598. tz *= tmp1X;
  94599. var bx = ny * tz - nz * ty;
  94600. var by = nz * tx - nx * tz;
  94601. var bz = nx * ty - ny * tx;
  94602. this.nor.init(nx, ny, nz);
  94603. this.tan.init(tx, ty, tz);
  94604. this.bin.init(bx, by, bz);
  94605. this.ac.preSolve(timeStep, invTimeStep);
  94606. this.t3.preSolve(timeStep, invTimeStep);
  94607. };
  94608. OIMO.PrismaticJoint.prototype.solve = function () {
  94609. this.ac.solve();
  94610. this.t3.solve();
  94611. };
  94612. OIMO.PrismaticJoint.prototype.postSolve = function () {
  94613. };
  94614. /**
  94615. * A slider joint allows for relative translation and relative rotation between two rigid bodies along the axis.
  94616. * @author saharan
  94617. * @author lo-th
  94618. */
  94619. OIMO.SliderJoint = function (config, lowerTranslation, upperTranslation) {
  94620. OIMO.Joint.call(this, config);
  94621. this.type = OIMO.JOINT_SLIDER;
  94622. // The first axis in local coordinate system.
  94623. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  94624. // The second axis in local coordinate system.
  94625. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  94626. var len;
  94627. this.localAxis1X = this.localAxis1.x;
  94628. this.localAxis1Y = this.localAxis1.y;
  94629. this.localAxis1Z = this.localAxis1.z;
  94630. this.localAngAxis1X = this.localAxis1Y * this.localAxis1X - this.localAxis1Z * this.localAxis1Z;
  94631. this.localAngAxis1Y = -this.localAxis1Z * this.localAxis1Y - this.localAxis1X * this.localAxis1X;
  94632. this.localAngAxis1Z = this.localAxis1X * this.localAxis1Z + this.localAxis1Y * this.localAxis1Y;
  94633. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  94634. this.localAngAxis1X *= len;
  94635. this.localAngAxis1Y *= len;
  94636. this.localAngAxis1Z *= len;
  94637. this.localAxis2X = this.localAxis2.x;
  94638. this.localAxis2Y = this.localAxis2.y;
  94639. this.localAxis2Z = this.localAxis2.z;
  94640. // make angle axis 2
  94641. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  94642. var tarc = arc.elements;
  94643. this.localAngAxis2X = this.localAngAxis1X * tarc[0] + this.localAngAxis1Y * tarc[1] + this.localAngAxis1Z * tarc[2];
  94644. this.localAngAxis2Y = this.localAngAxis1X * tarc[3] + this.localAngAxis1Y * tarc[4] + this.localAngAxis1Z * tarc[5];
  94645. this.localAngAxis2Z = this.localAngAxis1X * tarc[6] + this.localAngAxis1Y * tarc[7] + this.localAngAxis1Z * tarc[8];
  94646. this.nor = new OIMO.Vec3();
  94647. this.tan = new OIMO.Vec3();
  94648. this.bin = new OIMO.Vec3();
  94649. // The limit and motor for the rotation
  94650. this.rotationalLimitMotor = new OIMO.LimitMotor(this.nor, false);
  94651. this.r3 = new OIMO.Rotational3Constraint(this, this.rotationalLimitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  94652. // The limit and motor for the translation.
  94653. this.translationalLimitMotor = new OIMO.LimitMotor(this.nor, true);
  94654. this.translationalLimitMotor.lowerLimit = lowerTranslation;
  94655. this.translationalLimitMotor.upperLimit = upperTranslation;
  94656. this.t3 = new OIMO.Translational3Constraint(this, this.translationalLimitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  94657. };
  94658. OIMO.SliderJoint.prototype = Object.create(OIMO.Joint.prototype);
  94659. OIMO.SliderJoint.prototype.constructor = OIMO.SliderJoint;
  94660. OIMO.SliderJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  94661. var tmpM;
  94662. var tmp1X;
  94663. var tmp1Y;
  94664. var tmp1Z;
  94665. this.updateAnchorPoints();
  94666. tmpM = this.body1.rotation.elements;
  94667. var axis1X = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  94668. var axis1Y = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  94669. var axis1Z = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  94670. var angAxis1X = this.localAngAxis1X * tmpM[0] + this.localAngAxis1Y * tmpM[1] + this.localAngAxis1Z * tmpM[2];
  94671. var angAxis1Y = this.localAngAxis1X * tmpM[3] + this.localAngAxis1Y * tmpM[4] + this.localAngAxis1Z * tmpM[5];
  94672. var angAxis1Z = this.localAngAxis1X * tmpM[6] + this.localAngAxis1Y * tmpM[7] + this.localAngAxis1Z * tmpM[8];
  94673. tmpM = this.body2.rotation.elements;
  94674. var axis2X = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  94675. var axis2Y = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  94676. var axis2Z = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  94677. var angAxis2X = this.localAngAxis2X * tmpM[0] + this.localAngAxis2Y * tmpM[1] + this.localAngAxis2Z * tmpM[2];
  94678. var angAxis2Y = this.localAngAxis2X * tmpM[3] + this.localAngAxis2Y * tmpM[4] + this.localAngAxis2Z * tmpM[5];
  94679. var angAxis2Z = this.localAngAxis2X * tmpM[6] + this.localAngAxis2Y * tmpM[7] + this.localAngAxis2Z * tmpM[8];
  94680. var nx = axis1X * this.body2.inverseMass + axis2X * this.body1.inverseMass;
  94681. var ny = axis1Y * this.body2.inverseMass + axis2Y * this.body1.inverseMass;
  94682. var nz = axis1Z * this.body2.inverseMass + axis2Z * this.body1.inverseMass;
  94683. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  94684. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  94685. nx *= tmp1X;
  94686. ny *= tmp1X;
  94687. nz *= tmp1X;
  94688. var tx = ny * nx - nz * nz;
  94689. var ty = -nz * ny - nx * nx;
  94690. var tz = nx * nz + ny * ny;
  94691. tmp1X = 1 / OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  94692. tx *= tmp1X;
  94693. ty *= tmp1X;
  94694. tz *= tmp1X;
  94695. var bx = ny * tz - nz * ty;
  94696. var by = nz * tx - nx * tz;
  94697. var bz = nx * ty - ny * tx;
  94698. this.nor.init(nx, ny, nz);
  94699. this.tan.init(tx, ty, tz);
  94700. this.bin.init(bx, by, bz);
  94701. // ----------------------------------------------
  94702. // calculate hinge angle
  94703. // ----------------------------------------------
  94704. if (
  94705. nx * (angAxis1Y * angAxis2Z - angAxis1Z * angAxis2Y) +
  94706. ny * (angAxis1Z * angAxis2X - angAxis1X * angAxis2Z) +
  94707. nz * (angAxis1X * angAxis2Y - angAxis1Y * angAxis2X) < 0
  94708. ) {
  94709. this.rotationalLimitMotor.angle = -this.acosClamp(angAxis1X * angAxis2X + angAxis1Y * angAxis2Y + angAxis1Z * angAxis2Z);
  94710. } else {
  94711. this.rotationalLimitMotor.angle = this.acosClamp(angAxis1X * angAxis2X + angAxis1Y * angAxis2Y + angAxis1Z * angAxis2Z);
  94712. }
  94713. // angular error
  94714. tmp1X = axis1Y * axis2Z - axis1Z * axis2Y;
  94715. tmp1Y = axis1Z * axis2X - axis1X * axis2Z;
  94716. tmp1Z = axis1X * axis2Y - axis1Y * axis2X;
  94717. this.r3.limitMotor2.angle = tx * tmp1X + ty * tmp1Y + tz * tmp1Z;
  94718. this.r3.limitMotor3.angle = bx * tmp1X + by * tmp1Y + bz * tmp1Z;
  94719. this.r3.preSolve(timeStep, invTimeStep);
  94720. this.t3.preSolve(timeStep, invTimeStep);
  94721. };
  94722. OIMO.SliderJoint.prototype.solve = function () {
  94723. this.r3.solve();
  94724. this.t3.solve();
  94725. };
  94726. OIMO.SliderJoint.prototype.postSolve = function () {
  94727. };
  94728. OIMO.SliderJoint.prototype.acosClamp = function (cos) {
  94729. if (cos > 1) return 0;
  94730. else if (cos < -1) return OIMO.PI;
  94731. else return OIMO.acos(cos);
  94732. };
  94733. /**
  94734. * A wheel joint allows for relative rotation between two rigid bodies along two axes.
  94735. * The wheel joint also allows for relative translation for the suspension.
  94736. * @author saharan
  94737. * @author lo-th
  94738. */
  94739. OIMO.WheelJoint = function (config) {
  94740. OIMO.Joint.call(this, config);
  94741. this.type = OIMO.JOINT_WHEEL;
  94742. // The first axis in local coordinate system.
  94743. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  94744. // The second axis in local coordinate system.
  94745. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  94746. var len;
  94747. this.localAxis1X = this.localAxis1.x;
  94748. this.localAxis1Y = this.localAxis1.y;
  94749. this.localAxis1Z = this.localAxis1.z;
  94750. this.localAxis2X = this.localAxis2.x;
  94751. this.localAxis2Y = this.localAxis2.y;
  94752. this.localAxis2Z = this.localAxis2.z;
  94753. var dot = this.localAxis1X * this.localAxis2X + this.localAxis1Y * this.localAxis2Y + this.localAxis1Z * this.localAxis2Z;
  94754. if (dot > -1 && dot < 1) {
  94755. this.localAngAxis1X = this.localAxis2X - dot * this.localAxis1X;
  94756. this.localAngAxis1Y = this.localAxis2Y - dot * this.localAxis1Y;
  94757. this.localAngAxis1Z = this.localAxis2Z - dot * this.localAxis1Z;
  94758. this.localAngAxis2X = this.localAxis1X - dot * this.localAxis2X;
  94759. this.localAngAxis2Y = this.localAxis1Y - dot * this.localAxis2Y;
  94760. this.localAngAxis2Z = this.localAxis1Z - dot * this.localAxis2Z;
  94761. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  94762. this.localAngAxis1X *= len;
  94763. this.localAngAxis1Y *= len;
  94764. this.localAngAxis1Z *= len;
  94765. len = 1 / OIMO.sqrt(this.localAngAxis2X * this.localAngAxis2X + this.localAngAxis2Y * this.localAngAxis2Y + this.localAngAxis2Z * this.localAngAxis2Z);
  94766. this.localAngAxis2X *= len;
  94767. this.localAngAxis2Y *= len;
  94768. this.localAngAxis2Z *= len;
  94769. } else {
  94770. this.localAngAxis1X = this.localAxis1Y * this.localAxis1X - this.localAxis1Z * this.localAxis1Z;
  94771. this.localAngAxis1Y = -this.localAxis1Z * this.localAxis1Y - this.localAxis1X * this.localAxis1X;
  94772. this.localAngAxis1Z = this.localAxis1X * this.localAxis1Z + this.localAxis1Y * this.localAxis1Y;
  94773. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  94774. this.localAngAxis1X *= len;
  94775. this.localAngAxis1Y *= len;
  94776. this.localAngAxis1Z *= len;
  94777. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  94778. var tarc = arc.elements;
  94779. this.localAngAxis2X = this.localAngAxis1X * tarc[0] + this.localAngAxis1Y * tarc[1] + this.localAngAxis1Z * tarc[2];
  94780. this.localAngAxis2Y = this.localAngAxis1X * tarc[3] + this.localAngAxis1Y * tarc[4] + this.localAngAxis1Z * tarc[5];
  94781. this.localAngAxis2Z = this.localAngAxis1X * tarc[6] + this.localAngAxis1Y * tarc[7] + this.localAngAxis1Z * tarc[8];
  94782. }
  94783. this.nor = new OIMO.Vec3();
  94784. this.tan = new OIMO.Vec3();
  94785. this.bin = new OIMO.Vec3();
  94786. // The translational limit and motor information of the joint.
  94787. this.translationalLimitMotor = new OIMO.LimitMotor(this.tan, true);
  94788. this.translationalLimitMotor.frequency = 8;
  94789. this.translationalLimitMotor.dampingRatio = 1;
  94790. // The first rotational limit and motor information of the joint.
  94791. this.rotationalLimitMotor1 = new OIMO.LimitMotor(this.tan, false);
  94792. // The second rotational limit and motor information of the joint.
  94793. this.rotationalLimitMotor2 = new OIMO.LimitMotor(this.bin, false);
  94794. this.t3 = new OIMO.Translational3Constraint(this, new OIMO.LimitMotor(this.nor, true), this.translationalLimitMotor, new OIMO.LimitMotor(this.bin, true));
  94795. this.t3.weight = 1;
  94796. this.r3 = new OIMO.Rotational3Constraint(this, new OIMO.LimitMotor(this.nor, true), this.rotationalLimitMotor1, this.rotationalLimitMotor2);
  94797. };
  94798. OIMO.WheelJoint.prototype = Object.create(OIMO.Joint.prototype);
  94799. OIMO.WheelJoint.prototype.constructor = OIMO.WheelJoint;
  94800. OIMO.WheelJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  94801. var tmpM;
  94802. var tmp1X;
  94803. var tmp1Y;
  94804. var tmp1Z;
  94805. this.updateAnchorPoints();
  94806. tmpM = this.body1.rotation.elements;
  94807. var x1 = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  94808. var y1 = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  94809. var z1 = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  94810. var angAxis1X = this.localAngAxis1X * tmpM[0] + this.localAngAxis1Y * tmpM[1] + this.localAngAxis1Z * tmpM[2];
  94811. var angAxis1Y = this.localAngAxis1X * tmpM[3] + this.localAngAxis1Y * tmpM[4] + this.localAngAxis1Z * tmpM[5];
  94812. var angAxis1Z = this.localAngAxis1X * tmpM[6] + this.localAngAxis1Y * tmpM[7] + this.localAngAxis1Z * tmpM[8];
  94813. tmpM = this.body2.rotation.elements;
  94814. var x2 = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  94815. var y2 = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  94816. var z2 = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  94817. var angAxis2X = this.localAngAxis2X * tmpM[0] + this.localAngAxis2Y * tmpM[1] + this.localAngAxis2Z * tmpM[2];
  94818. var angAxis2Y = this.localAngAxis2X * tmpM[3] + this.localAngAxis2Y * tmpM[4] + this.localAngAxis2Z * tmpM[5];
  94819. var angAxis2Z = this.localAngAxis2X * tmpM[6] + this.localAngAxis2Y * tmpM[7] + this.localAngAxis2Z * tmpM[8];
  94820. this.r3.limitMotor1.angle = x1 * x2 + y1 * y2 + z1 * z2;
  94821. if (x1 * (angAxis1Y * z2 - angAxis1Z * y2) + y1 * (angAxis1Z * x2 - angAxis1X * z2) + z1 * (angAxis1X * y2 - angAxis1Y * x2) < 0) {
  94822. this.rotationalLimitMotor1.angle = -this.acosClamp(angAxis1X * x2 + angAxis1Y * y2 + angAxis1Z * z2);
  94823. } else {
  94824. this.rotationalLimitMotor1.angle = this.acosClamp(angAxis1X * x2 + angAxis1Y * y2 + angAxis1Z * z2);
  94825. }
  94826. if (x2 * (angAxis2Y * z1 - angAxis2Z * y1) + y2 * (angAxis2Z * x1 - angAxis2X * z1) + z2 * (angAxis2X * y1 - angAxis2Y * x1) < 0) {
  94827. this.rotationalLimitMotor2.angle = this.acosClamp(angAxis2X * x1 + angAxis2Y * y1 + angAxis2Z * z1);
  94828. } else {
  94829. this.rotationalLimitMotor2.angle = -this.acosClamp(angAxis2X * x1 + angAxis2Y * y1 + angAxis2Z * z1);
  94830. }
  94831. var nx = y2 * z1 - z2 * y1;
  94832. var ny = z2 * x1 - x2 * z1;
  94833. var nz = x2 * y1 - y2 * x1;
  94834. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  94835. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  94836. nx *= tmp1X;
  94837. ny *= tmp1X;
  94838. nz *= tmp1X;
  94839. var tx = ny * z2 - nz * y2;
  94840. var ty = nz * x2 - nx * z2;
  94841. var tz = nx * y2 - ny * x2;
  94842. tmp1X = OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  94843. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  94844. tx *= tmp1X;
  94845. ty *= tmp1X;
  94846. tz *= tmp1X;
  94847. var bx = y1 * nz - z1 * ny;
  94848. var by = z1 * nx - x1 * nz;
  94849. var bz = x1 * ny - y1 * nx;
  94850. tmp1X = OIMO.sqrt(bx * bx + by * by + bz * bz);
  94851. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  94852. bx *= tmp1X;
  94853. by *= tmp1X;
  94854. bz *= tmp1X;
  94855. this.nor.init(nx, ny, nz);
  94856. this.tan.init(tx, ty, tz);
  94857. this.bin.init(bx, by, bz);
  94858. this.r3.preSolve(timeStep, invTimeStep);
  94859. this.t3.preSolve(timeStep, invTimeStep);
  94860. };
  94861. OIMO.WheelJoint.prototype.solve = function () {
  94862. this.r3.solve();
  94863. this.t3.solve();
  94864. };
  94865. OIMO.WheelJoint.prototype.postSolve = function () {
  94866. };
  94867. OIMO.WheelJoint.prototype.acosClamp = function (cos) {
  94868. if (cos > 1) return 0;
  94869. else if (cos < -1) return OIMO.PI;
  94870. else return OIMO.acos(cos);
  94871. };
  94872. /**
  94873. * An angular constraint for all axes for various joints.
  94874. * @author saharan
  94875. */
  94876. OIMO.AngularConstraint = function (joint, targetOrientation) {
  94877. this.joint = joint;
  94878. this.targetOrientation = new OIMO.Quat().invert(targetOrientation);
  94879. this.relativeOrientation = new OIMO.Quat();
  94880. this.ii1 = null;
  94881. this.ii2 = null;
  94882. this.dd = null;
  94883. this.vel = new OIMO.Vec3();
  94884. this.imp = new OIMO.Vec3();
  94885. this.rn0 = new OIMO.Vec3();
  94886. this.rn1 = new OIMO.Vec3();
  94887. this.rn2 = new OIMO.Vec3();
  94888. this.b1 = joint.body1;
  94889. this.b2 = joint.body2;
  94890. this.a1 = this.b1.angularVelocity;
  94891. this.a2 = this.b2.angularVelocity;
  94892. this.i1 = this.b1.inverseInertia;
  94893. this.i2 = this.b2.inverseInertia;
  94894. };
  94895. OIMO.AngularConstraint.prototype = {
  94896. constructor: OIMO.AngularConstraint,
  94897. preSolve: function (timeStep, invTimeStep) {
  94898. var inv, len, v, vv;
  94899. this.ii1 = this.i1.clone();
  94900. this.ii2 = this.i2.clone();
  94901. v = new OIMO.Mat33().add(this.ii1, this.ii2).elements;
  94902. 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]));
  94903. this.dd = new OIMO.Mat33(
  94904. v[4] * v[8] - v[5] * v[7], v[2] * v[7] - v[1] * v[8], v[1] * v[5] - v[2] * v[4],
  94905. v[5] * v[6] - v[3] * v[8], v[0] * v[8] - v[2] * v[6], v[2] * v[3] - v[0] * v[5],
  94906. v[3] * v[7] - v[4] * v[6], v[1] * v[6] - v[0] * v[7], v[0] * v[4] - v[1] * v[3]
  94907. ).multiply(inv);
  94908. this.relativeOrientation.invert(this.b1.orientation);
  94909. this.relativeOrientation.mul(this.targetOrientation, this.relativeOrientation);
  94910. this.relativeOrientation.mul(this.b2.orientation, this.relativeOrientation);
  94911. inv = this.relativeOrientation.s * 2;
  94912. this.vel.scale(this.relativeOrientation, inv);
  94913. len = this.vel.length();
  94914. if (len > 0.02) {
  94915. len = (0.02 - len) / len * invTimeStep * 0.05;
  94916. this.vel.scaleEqual(len);
  94917. } else {
  94918. this.vel.init();
  94919. }
  94920. this.rn1.mulMat(this.ii1, this.imp);
  94921. this.rn2.mulMat(this.ii2, this.imp);
  94922. this.a1.addEqual(this.rn1);
  94923. this.a2.subEqual(this.rn2);
  94924. },
  94925. solve: function () {
  94926. var r = this.a2.clone().subEqual(this.a1).subEqual(this.vel);
  94927. this.rn0.mulMat(this.dd, r);
  94928. this.rn1.mulMat(this.ii1, this.rn0);
  94929. this.rn2.mulMat(this.ii2, this.rn0);
  94930. this.imp.addEqual(this.rn0);
  94931. this.a1.addEqual(this.rn1);
  94932. this.a2.subEqual(this.rn2);
  94933. }
  94934. };
  94935. /**
  94936. * A linear constraint for all axes for various joints.
  94937. * @author saharan
  94938. */
  94939. OIMO.LinearConstraint = function (joint) {
  94940. this.m1 = NaN;
  94941. this.m2 = NaN;
  94942. this.ii1 = null;
  94943. this.ii2 = null;
  94944. this.dd = null;
  94945. this.r1x = NaN;
  94946. this.r1y = NaN;
  94947. this.r1z = NaN;
  94948. this.r2x = NaN;
  94949. this.r2y = NaN;
  94950. this.r2z = NaN;
  94951. this.ax1x = NaN;
  94952. this.ax1y = NaN;
  94953. this.ax1z = NaN;
  94954. this.ay1x = NaN;
  94955. this.ay1y = NaN;
  94956. this.ay1z = NaN;
  94957. this.az1x = NaN;
  94958. this.az1y = NaN;
  94959. this.az1z = NaN;
  94960. this.ax2x = NaN;
  94961. this.ax2y = NaN;
  94962. this.ax2z = NaN;
  94963. this.ay2x = NaN;
  94964. this.ay2y = NaN;
  94965. this.ay2z = NaN;
  94966. this.az2x = NaN;
  94967. this.az2y = NaN;
  94968. this.az2z = NaN;
  94969. this.vel = NaN;
  94970. this.velx = NaN;
  94971. this.vely = NaN;
  94972. this.velz = NaN;
  94973. this.joint = joint;
  94974. this.r1 = joint.relativeAnchorPoint1;
  94975. this.r2 = joint.relativeAnchorPoint2;
  94976. this.p1 = joint.anchorPoint1;
  94977. this.p2 = joint.anchorPoint2;
  94978. this.b1 = joint.body1;
  94979. this.b2 = joint.body2;
  94980. this.l1 = this.b1.linearVelocity;
  94981. this.l2 = this.b2.linearVelocity;
  94982. this.a1 = this.b1.angularVelocity;
  94983. this.a2 = this.b2.angularVelocity;
  94984. this.i1 = this.b1.inverseInertia;
  94985. this.i2 = this.b2.inverseInertia;
  94986. this.impx = 0;
  94987. this.impy = 0;
  94988. this.impz = 0;
  94989. }
  94990. OIMO.LinearConstraint.prototype = {
  94991. constructor: OIMO.LinearConstraint,
  94992. preSolve: function (timeStep, invTimeStep) {
  94993. this.r1x = this.r1.x;
  94994. this.r1y = this.r1.y;
  94995. this.r1z = this.r1.z;
  94996. this.r2x = this.r2.x;
  94997. this.r2y = this.r2.y;
  94998. this.r2z = this.r2.z;
  94999. this.m1 = this.b1.inverseMass;
  95000. this.m2 = this.b2.inverseMass;
  95001. this.ii1 = this.i1.clone();
  95002. this.ii2 = this.i2.clone();
  95003. var ii1 = this.ii1.elements;
  95004. var ii2 = this.ii2.elements;
  95005. this.ax1x = this.r1z * ii1[1] + -this.r1y * ii1[2];
  95006. this.ax1y = this.r1z * ii1[4] + -this.r1y * ii1[5];
  95007. this.ax1z = this.r1z * ii1[7] + -this.r1y * ii1[8];
  95008. this.ay1x = -this.r1z * ii1[0] + this.r1x * ii1[2];
  95009. this.ay1y = -this.r1z * ii1[3] + this.r1x * ii1[5];
  95010. this.ay1z = -this.r1z * ii1[6] + this.r1x * ii1[8];
  95011. this.az1x = this.r1y * ii1[0] + -this.r1x * ii1[1];
  95012. this.az1y = this.r1y * ii1[3] + -this.r1x * ii1[4];
  95013. this.az1z = this.r1y * ii1[6] + -this.r1x * ii1[7];
  95014. this.ax2x = this.r2z * ii2[1] + -this.r2y * ii2[2];
  95015. this.ax2y = this.r2z * ii2[4] + -this.r2y * ii2[5];
  95016. this.ax2z = this.r2z * ii2[7] + -this.r2y * ii2[8];
  95017. this.ay2x = -this.r2z * ii2[0] + this.r2x * ii2[2];
  95018. this.ay2y = -this.r2z * ii2[3] + this.r2x * ii2[5];
  95019. this.ay2z = -this.r2z * ii2[6] + this.r2x * ii2[8];
  95020. this.az2x = this.r2y * ii2[0] + -this.r2x * ii2[1];
  95021. this.az2y = this.r2y * ii2[3] + -this.r2x * ii2[4];
  95022. this.az2z = this.r2y * ii2[6] + -this.r2x * ii2[7];
  95023. // calculate point-to-point mass matrix
  95024. // from impulse equation
  95025. //
  95026. // M = ([/m] - [r^][/I][r^]) ^ -1
  95027. //
  95028. // where
  95029. //
  95030. // [/m] = |1/m, 0, 0|
  95031. // |0, 1/m, 0|
  95032. // |0, 0, 1/m|
  95033. //
  95034. // [r^] = |0, -rz, ry|
  95035. // |rz, 0, -rx|
  95036. // |-ry, rx, 0|
  95037. //
  95038. // [/I] = Inverted moment inertia
  95039. var rxx = this.m1 + this.m2;
  95040. var kk = new OIMO.Mat33(rxx, 0, 0, 0, rxx, 0, 0, 0, rxx);
  95041. var k = kk.elements;
  95042. k[0] += ii1[4] * this.r1z * this.r1z - (ii1[7] + ii1[5]) * this.r1y * this.r1z + ii1[8] * this.r1y * this.r1y;
  95043. k[1] += (ii1[6] * this.r1y + ii1[5] * this.r1x) * this.r1z - ii1[3] * this.r1z * this.r1z - ii1[8] * this.r1x * this.r1y;
  95044. k[2] += (ii1[3] * this.r1y - ii1[4] * this.r1x) * this.r1z - ii1[6] * this.r1y * this.r1y + ii1[7] * this.r1x * this.r1y;
  95045. k[3] += (ii1[2] * this.r1y + ii1[7] * this.r1x) * this.r1z - ii1[1] * this.r1z * this.r1z - ii1[8] * this.r1x * this.r1y;
  95046. k[4] += ii1[0] * this.r1z * this.r1z - (ii1[6] + ii1[2]) * this.r1x * this.r1z + ii1[8] * this.r1x * this.r1x;
  95047. k[5] += (ii1[1] * this.r1x - ii1[0] * this.r1y) * this.r1z - ii1[7] * this.r1x * this.r1x + ii1[6] * this.r1x * this.r1y;
  95048. k[6] += (ii1[1] * this.r1y - ii1[4] * this.r1x) * this.r1z - ii1[2] * this.r1y * this.r1y + ii1[5] * this.r1x * this.r1y;
  95049. k[7] += (ii1[3] * this.r1x - ii1[0] * this.r1y) * this.r1z - ii1[5] * this.r1x * this.r1x + ii1[2] * this.r1x * this.r1y;
  95050. k[8] += ii1[0] * this.r1y * this.r1y - (ii1[3] + ii1[1]) * this.r1x * this.r1y + ii1[4] * this.r1x * this.r1x;
  95051. k[0] += ii2[4] * this.r2z * this.r2z - (ii2[7] + ii2[5]) * this.r2y * this.r2z + ii2[8] * this.r2y * this.r2y;
  95052. k[1] += (ii2[6] * this.r2y + ii2[5] * this.r2x) * this.r2z - ii2[3] * this.r2z * this.r2z - ii2[8] * this.r2x * this.r2y;
  95053. k[2] += (ii2[3] * this.r2y - ii2[4] * this.r2x) * this.r2z - ii2[6] * this.r2y * this.r2y + ii2[7] * this.r2x * this.r2y;
  95054. k[3] += (ii2[2] * this.r2y + ii2[7] * this.r2x) * this.r2z - ii2[1] * this.r2z * this.r2z - ii2[8] * this.r2x * this.r2y;
  95055. k[4] += ii2[0] * this.r2z * this.r2z - (ii2[6] + ii2[2]) * this.r2x * this.r2z + ii2[8] * this.r2x * this.r2x;
  95056. k[5] += (ii2[1] * this.r2x - ii2[0] * this.r2y) * this.r2z - ii2[7] * this.r2x * this.r2x + ii2[6] * this.r2x * this.r2y;
  95057. k[6] += (ii2[1] * this.r2y - ii2[4] * this.r2x) * this.r2z - ii2[2] * this.r2y * this.r2y + ii2[5] * this.r2x * this.r2y;
  95058. k[7] += (ii2[3] * this.r2x - ii2[0] * this.r2y) * this.r2z - ii2[5] * this.r2x * this.r2x + ii2[2] * this.r2x * this.r2y;
  95059. k[8] += ii2[0] * this.r2y * this.r2y - (ii2[3] + ii2[1]) * this.r2x * this.r2y + ii2[4] * this.r2x * this.r2x;
  95060. 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]));
  95061. this.dd = new OIMO.Mat33(
  95062. k[4] * k[8] - k[5] * k[7], k[2] * k[7] - k[1] * k[8], k[1] * k[5] - k[2] * k[4],
  95063. k[5] * k[6] - k[3] * k[8], k[0] * k[8] - k[2] * k[6], k[2] * k[3] - k[0] * k[5],
  95064. k[3] * k[7] - k[4] * k[6], k[1] * k[6] - k[0] * k[7], k[0] * k[4] - k[1] * k[3]
  95065. ).multiply(inv);
  95066. this.velx = this.p2.x - this.p1.x;
  95067. this.vely = this.p2.y - this.p1.y;
  95068. this.velz = this.p2.z - this.p1.z;
  95069. var len = OIMO.sqrt(this.velx * this.velx + this.vely * this.vely + this.velz * this.velz);
  95070. if (len > 0.005) {
  95071. len = (0.005 - len) / len * invTimeStep * 0.05;
  95072. this.velx *= len;
  95073. this.vely *= len;
  95074. this.velz *= len;
  95075. } else {
  95076. this.velx = 0;
  95077. this.vely = 0;
  95078. this.velz = 0;
  95079. }
  95080. this.impx *= 0.95;
  95081. this.impy *= 0.95;
  95082. this.impz *= 0.95;
  95083. this.l1.x += this.impx * this.m1;
  95084. this.l1.y += this.impy * this.m1;
  95085. this.l1.z += this.impz * this.m1;
  95086. this.a1.x += this.impx * this.ax1x + this.impy * this.ay1x + this.impz * this.az1x;
  95087. this.a1.y += this.impx * this.ax1y + this.impy * this.ay1y + this.impz * this.az1y;
  95088. this.a1.z += this.impx * this.ax1z + this.impy * this.ay1z + this.impz * this.az1z;
  95089. this.l2.x -= this.impx * this.m2;
  95090. this.l2.y -= this.impy * this.m2;
  95091. this.l2.z -= this.impz * this.m2;
  95092. this.a2.x -= this.impx * this.ax2x + this.impy * this.ay2x + this.impz * this.az2x;
  95093. this.a2.y -= this.impx * this.ax2y + this.impy * this.ay2y + this.impz * this.az2y;
  95094. this.a2.z -= this.impx * this.ax2z + this.impy * this.ay2z + this.impz * this.az2z;
  95095. },
  95096. solve: function () {
  95097. var d = this.dd.elements;
  95098. 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;
  95099. 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;
  95100. 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;
  95101. var nimpx = rvx * d[0] + rvy * d[1] + rvz * d[2];
  95102. var nimpy = rvx * d[3] + rvy * d[4] + rvz * d[5];
  95103. var nimpz = rvx * d[6] + rvy * d[7] + rvz * d[8];
  95104. this.impx += nimpx;
  95105. this.impy += nimpy;
  95106. this.impz += nimpz;
  95107. this.l1.x += nimpx * this.m1;
  95108. this.l1.y += nimpy * this.m1;
  95109. this.l1.z += nimpz * this.m1;
  95110. this.a1.x += nimpx * this.ax1x + nimpy * this.ay1x + nimpz * this.az1x;
  95111. this.a1.y += nimpx * this.ax1y + nimpy * this.ay1y + nimpz * this.az1y;
  95112. this.a1.z += nimpx * this.ax1z + nimpy * this.ay1z + nimpz * this.az1z;
  95113. this.l2.x -= nimpx * this.m2;
  95114. this.l2.y -= nimpy * this.m2;
  95115. this.l2.z -= nimpz * this.m2;
  95116. this.a2.x -= nimpx * this.ax2x + nimpy * this.ay2x + nimpz * this.az2x;
  95117. this.a2.y -= nimpx * this.ax2y + nimpy * this.ay2y + nimpz * this.az2y;
  95118. this.a2.z -= nimpx * this.ax2z + nimpy * this.ay2z + nimpz * this.az2z;
  95119. }
  95120. }
  95121. /**
  95122. * A three-axis rotational constraint for various joints.
  95123. * @author saharan
  95124. */
  95125. OIMO.Rotational3Constraint = function (joint, limitMotor1, limitMotor2, limitMotor3) {
  95126. this.cfm1 = NaN;
  95127. this.cfm2 = NaN;
  95128. this.cfm3 = NaN;
  95129. this.i1e00 = NaN;
  95130. this.i1e01 = NaN;
  95131. this.i1e02 = NaN;
  95132. this.i1e10 = NaN;
  95133. this.i1e11 = NaN;
  95134. this.i1e12 = NaN;
  95135. this.i1e20 = NaN;
  95136. this.i1e21 = NaN;
  95137. this.i1e22 = NaN;
  95138. this.i2e00 = NaN;
  95139. this.i2e01 = NaN;
  95140. this.i2e02 = NaN;
  95141. this.i2e10 = NaN;
  95142. this.i2e11 = NaN;
  95143. this.i2e12 = NaN;
  95144. this.i2e20 = NaN;
  95145. this.i2e21 = NaN;
  95146. this.i2e22 = NaN;
  95147. this.ax1 = NaN;
  95148. this.ay1 = NaN;
  95149. this.az1 = NaN;
  95150. this.ax2 = NaN;
  95151. this.ay2 = NaN;
  95152. this.az2 = NaN;
  95153. this.ax3 = NaN;
  95154. this.ay3 = NaN;
  95155. this.az3 = NaN;
  95156. this.a1x1 = NaN; // jacoians
  95157. this.a1y1 = NaN;
  95158. this.a1z1 = NaN;
  95159. this.a2x1 = NaN;
  95160. this.a2y1 = NaN;
  95161. this.a2z1 = NaN;
  95162. this.a1x2 = NaN;
  95163. this.a1y2 = NaN;
  95164. this.a1z2 = NaN;
  95165. this.a2x2 = NaN;
  95166. this.a2y2 = NaN;
  95167. this.a2z2 = NaN;
  95168. this.a1x3 = NaN;
  95169. this.a1y3 = NaN;
  95170. this.a1z3 = NaN;
  95171. this.a2x3 = NaN;
  95172. this.a2y3 = NaN;
  95173. this.a2z3 = NaN;
  95174. this.lowerLimit1 = NaN;
  95175. this.upperLimit1 = NaN;
  95176. this.limitVelocity1 = NaN;
  95177. this.limitState1 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  95178. this.enableMotor1 = false;
  95179. this.motorSpeed1 = NaN;
  95180. this.maxMotorForce1 = NaN;
  95181. this.maxMotorImpulse1 = NaN;
  95182. this.lowerLimit2 = NaN;
  95183. this.upperLimit2 = NaN;
  95184. this.limitVelocity2 = NaN;
  95185. this.limitState2 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  95186. this.enableMotor2 = false;
  95187. this.motorSpeed2 = NaN;
  95188. this.maxMotorForce2 = NaN;
  95189. this.maxMotorImpulse2 = NaN;
  95190. this.lowerLimit3 = NaN;
  95191. this.upperLimit3 = NaN;
  95192. this.limitVelocity3 = NaN;
  95193. this.limitState3 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  95194. this.enableMotor3 = false;
  95195. this.motorSpeed3 = NaN;
  95196. this.maxMotorForce3 = NaN;
  95197. this.maxMotorImpulse3 = NaN;
  95198. this.k00 = NaN; // K = J*M*JT
  95199. this.k01 = NaN;
  95200. this.k02 = NaN;
  95201. this.k10 = NaN;
  95202. this.k11 = NaN;
  95203. this.k12 = NaN;
  95204. this.k20 = NaN;
  95205. this.k21 = NaN;
  95206. this.k22 = NaN;
  95207. this.kv00 = NaN; // diagonals without CFMs
  95208. this.kv11 = NaN;
  95209. this.kv22 = NaN;
  95210. this.dv00 = NaN; // ...inverted
  95211. this.dv11 = NaN;
  95212. this.dv22 = NaN;
  95213. this.d00 = NaN; // K^-1
  95214. this.d01 = NaN;
  95215. this.d02 = NaN;
  95216. this.d10 = NaN;
  95217. this.d11 = NaN;
  95218. this.d12 = NaN;
  95219. this.d20 = NaN;
  95220. this.d21 = NaN;
  95221. this.d22 = NaN;
  95222. this.limitMotor1 = limitMotor1;
  95223. this.limitMotor2 = limitMotor2;
  95224. this.limitMotor3 = limitMotor3;
  95225. this.b1 = joint.body1;
  95226. this.b2 = joint.body2;
  95227. this.a1 = this.b1.angularVelocity;
  95228. this.a2 = this.b2.angularVelocity;
  95229. this.i1 = this.b1.inverseInertia;
  95230. this.i2 = this.b2.inverseInertia;
  95231. this.limitImpulse1 = 0;
  95232. this.motorImpulse1 = 0;
  95233. this.limitImpulse2 = 0;
  95234. this.motorImpulse2 = 0;
  95235. this.limitImpulse3 = 0;
  95236. this.motorImpulse3 = 0;
  95237. }
  95238. OIMO.Rotational3Constraint.prototype = {
  95239. constructor: OIMO.Rotational3Constraint,
  95240. preSolve: function (timeStep, invTimeStep) {
  95241. this.ax1 = this.limitMotor1.axis.x;
  95242. this.ay1 = this.limitMotor1.axis.y;
  95243. this.az1 = this.limitMotor1.axis.z;
  95244. this.ax2 = this.limitMotor2.axis.x;
  95245. this.ay2 = this.limitMotor2.axis.y;
  95246. this.az2 = this.limitMotor2.axis.z;
  95247. this.ax3 = this.limitMotor3.axis.x;
  95248. this.ay3 = this.limitMotor3.axis.y;
  95249. this.az3 = this.limitMotor3.axis.z;
  95250. this.lowerLimit1 = this.limitMotor1.lowerLimit;
  95251. this.upperLimit1 = this.limitMotor1.upperLimit;
  95252. this.motorSpeed1 = this.limitMotor1.motorSpeed;
  95253. this.maxMotorForce1 = this.limitMotor1.maxMotorForce;
  95254. this.enableMotor1 = this.maxMotorForce1 > 0;
  95255. this.lowerLimit2 = this.limitMotor2.lowerLimit;
  95256. this.upperLimit2 = this.limitMotor2.upperLimit;
  95257. this.motorSpeed2 = this.limitMotor2.motorSpeed;
  95258. this.maxMotorForce2 = this.limitMotor2.maxMotorForce;
  95259. this.enableMotor2 = this.maxMotorForce2 > 0;
  95260. this.lowerLimit3 = this.limitMotor3.lowerLimit;
  95261. this.upperLimit3 = this.limitMotor3.upperLimit;
  95262. this.motorSpeed3 = this.limitMotor3.motorSpeed;
  95263. this.maxMotorForce3 = this.limitMotor3.maxMotorForce;
  95264. this.enableMotor3 = this.maxMotorForce3 > 0;
  95265. var ti1 = this.i1.elements;
  95266. var ti2 = this.i2.elements;
  95267. this.i1e00 = ti1[0];
  95268. this.i1e01 = ti1[1];
  95269. this.i1e02 = ti1[2];
  95270. this.i1e10 = ti1[3];
  95271. this.i1e11 = ti1[4];
  95272. this.i1e12 = ti1[5];
  95273. this.i1e20 = ti1[6];
  95274. this.i1e21 = ti1[7];
  95275. this.i1e22 = ti1[8];
  95276. this.i2e00 = ti2[0];
  95277. this.i2e01 = ti2[1];
  95278. this.i2e02 = ti2[2];
  95279. this.i2e10 = ti2[3];
  95280. this.i2e11 = ti2[4];
  95281. this.i2e12 = ti2[5];
  95282. this.i2e20 = ti2[6];
  95283. this.i2e21 = ti2[7];
  95284. this.i2e22 = ti2[8];
  95285. var frequency1 = this.limitMotor1.frequency;
  95286. var frequency2 = this.limitMotor2.frequency;
  95287. var frequency3 = this.limitMotor3.frequency;
  95288. var enableSpring1 = frequency1 > 0;
  95289. var enableSpring2 = frequency2 > 0;
  95290. var enableSpring3 = frequency3 > 0;
  95291. var enableLimit1 = this.lowerLimit1 <= this.upperLimit1;
  95292. var enableLimit2 = this.lowerLimit2 <= this.upperLimit2;
  95293. var enableLimit3 = this.lowerLimit3 <= this.upperLimit3;
  95294. var angle1 = this.limitMotor1.angle;
  95295. if (enableLimit1) {
  95296. if (this.lowerLimit1 == this.upperLimit1) {
  95297. if (this.limitState1 != 0) {
  95298. this.limitState1 = 0;
  95299. this.limitImpulse1 = 0;
  95300. }
  95301. this.limitVelocity1 = this.lowerLimit1 - angle1;
  95302. } else if (angle1 < this.lowerLimit1) {
  95303. if (this.limitState1 != -1) {
  95304. this.limitState1 = -1;
  95305. this.limitImpulse1 = 0;
  95306. }
  95307. this.limitVelocity1 = this.lowerLimit1 - angle1;
  95308. } else if (angle1 > this.upperLimit1) {
  95309. if (this.limitState1 != 1) {
  95310. this.limitState1 = 1;
  95311. this.limitImpulse1 = 0;
  95312. }
  95313. this.limitVelocity1 = this.upperLimit1 - angle1;
  95314. } else {
  95315. this.limitState1 = 2;
  95316. this.limitImpulse1 = 0;
  95317. this.limitVelocity1 = 0;
  95318. }
  95319. if (!enableSpring1) {
  95320. if (this.limitVelocity1 > 0.02) this.limitVelocity1 -= 0.02;
  95321. else if (this.limitVelocity1 < -0.02) this.limitVelocity1 += 0.02;
  95322. else this.limitVelocity1 = 0;
  95323. }
  95324. } else {
  95325. this.limitState1 = 2;
  95326. this.limitImpulse1 = 0;
  95327. }
  95328. var angle2 = this.limitMotor2.angle;
  95329. if (enableLimit2) {
  95330. if (this.lowerLimit2 == this.upperLimit2) {
  95331. if (this.limitState2 != 0) {
  95332. this.limitState2 = 0;
  95333. this.limitImpulse2 = 0;
  95334. }
  95335. this.limitVelocity2 = this.lowerLimit2 - angle2;
  95336. } else if (angle2 < this.lowerLimit2) {
  95337. if (this.limitState2 != -1) {
  95338. this.limitState2 = -1;
  95339. this.limitImpulse2 = 0;
  95340. }
  95341. this.limitVelocity2 = this.lowerLimit2 - angle2;
  95342. } else if (angle2 > this.upperLimit2) {
  95343. if (this.limitState2 != 1) {
  95344. this.limitState2 = 1;
  95345. this.limitImpulse2 = 0;
  95346. }
  95347. this.limitVelocity2 = this.upperLimit2 - angle2;
  95348. } else {
  95349. this.limitState2 = 2;
  95350. this.limitImpulse2 = 0;
  95351. this.limitVelocity2 = 0;
  95352. }
  95353. if (!enableSpring2) {
  95354. if (this.limitVelocity2 > 0.02) this.limitVelocity2 -= 0.02;
  95355. else if (this.limitVelocity2 < -0.02) this.limitVelocity2 += 0.02;
  95356. else this.limitVelocity2 = 0;
  95357. }
  95358. } else {
  95359. this.limitState2 = 2;
  95360. this.limitImpulse2 = 0;
  95361. }
  95362. var angle3 = this.limitMotor3.angle;
  95363. if (enableLimit3) {
  95364. if (this.lowerLimit3 == this.upperLimit3) {
  95365. if (this.limitState3 != 0) {
  95366. this.limitState3 = 0;
  95367. this.limitImpulse3 = 0;
  95368. }
  95369. this.limitVelocity3 = this.lowerLimit3 - angle3;
  95370. } else if (angle3 < this.lowerLimit3) {
  95371. if (this.limitState3 != -1) {
  95372. this.limitState3 = -1;
  95373. this.limitImpulse3 = 0;
  95374. }
  95375. this.limitVelocity3 = this.lowerLimit3 - angle3;
  95376. } else if (angle3 > this.upperLimit3) {
  95377. if (this.limitState3 != 1) {
  95378. this.limitState3 = 1;
  95379. this.limitImpulse3 = 0;
  95380. }
  95381. this.limitVelocity3 = this.upperLimit3 - angle3;
  95382. } else {
  95383. this.limitState3 = 2;
  95384. this.limitImpulse3 = 0;
  95385. this.limitVelocity3 = 0;
  95386. }
  95387. if (!enableSpring3) {
  95388. if (this.limitVelocity3 > 0.02) this.limitVelocity3 -= 0.02;
  95389. else if (this.limitVelocity3 < -0.02) this.limitVelocity3 += 0.02;
  95390. else this.limitVelocity3 = 0;
  95391. }
  95392. } else {
  95393. this.limitState3 = 2;
  95394. this.limitImpulse3 = 0;
  95395. }
  95396. if (this.enableMotor1 && (this.limitState1 != 0 || enableSpring1)) {
  95397. this.maxMotorImpulse1 = this.maxMotorForce1 * timeStep;
  95398. } else {
  95399. this.motorImpulse1 = 0;
  95400. this.maxMotorImpulse1 = 0;
  95401. }
  95402. if (this.enableMotor2 && (this.limitState2 != 0 || enableSpring2)) {
  95403. this.maxMotorImpulse2 = this.maxMotorForce2 * timeStep;
  95404. } else {
  95405. this.motorImpulse2 = 0;
  95406. this.maxMotorImpulse2 = 0;
  95407. }
  95408. if (this.enableMotor3 && (this.limitState3 != 0 || enableSpring3)) {
  95409. this.maxMotorImpulse3 = this.maxMotorForce3 * timeStep;
  95410. } else {
  95411. this.motorImpulse3 = 0;
  95412. this.maxMotorImpulse3 = 0;
  95413. }
  95414. // build jacobians
  95415. this.a1x1 = this.ax1 * this.i1e00 + this.ay1 * this.i1e01 + this.az1 * this.i1e02;
  95416. this.a1y1 = this.ax1 * this.i1e10 + this.ay1 * this.i1e11 + this.az1 * this.i1e12;
  95417. this.a1z1 = this.ax1 * this.i1e20 + this.ay1 * this.i1e21 + this.az1 * this.i1e22;
  95418. this.a2x1 = this.ax1 * this.i2e00 + this.ay1 * this.i2e01 + this.az1 * this.i2e02;
  95419. this.a2y1 = this.ax1 * this.i2e10 + this.ay1 * this.i2e11 + this.az1 * this.i2e12;
  95420. this.a2z1 = this.ax1 * this.i2e20 + this.ay1 * this.i2e21 + this.az1 * this.i2e22;
  95421. this.a1x2 = this.ax2 * this.i1e00 + this.ay2 * this.i1e01 + this.az2 * this.i1e02;
  95422. this.a1y2 = this.ax2 * this.i1e10 + this.ay2 * this.i1e11 + this.az2 * this.i1e12;
  95423. this.a1z2 = this.ax2 * this.i1e20 + this.ay2 * this.i1e21 + this.az2 * this.i1e22;
  95424. this.a2x2 = this.ax2 * this.i2e00 + this.ay2 * this.i2e01 + this.az2 * this.i2e02;
  95425. this.a2y2 = this.ax2 * this.i2e10 + this.ay2 * this.i2e11 + this.az2 * this.i2e12;
  95426. this.a2z2 = this.ax2 * this.i2e20 + this.ay2 * this.i2e21 + this.az2 * this.i2e22;
  95427. this.a1x3 = this.ax3 * this.i1e00 + this.ay3 * this.i1e01 + this.az3 * this.i1e02;
  95428. this.a1y3 = this.ax3 * this.i1e10 + this.ay3 * this.i1e11 + this.az3 * this.i1e12;
  95429. this.a1z3 = this.ax3 * this.i1e20 + this.ay3 * this.i1e21 + this.az3 * this.i1e22;
  95430. this.a2x3 = this.ax3 * this.i2e00 + this.ay3 * this.i2e01 + this.az3 * this.i2e02;
  95431. this.a2y3 = this.ax3 * this.i2e10 + this.ay3 * this.i2e11 + this.az3 * this.i2e12;
  95432. this.a2z3 = this.ax3 * this.i2e20 + this.ay3 * this.i2e21 + this.az3 * this.i2e22;
  95433. // build an impulse matrix
  95434. this.k00 = this.ax1 * (this.a1x1 + this.a2x1) + this.ay1 * (this.a1y1 + this.a2y1) + this.az1 * (this.a1z1 + this.a2z1);
  95435. this.k01 = this.ax1 * (this.a1x2 + this.a2x2) + this.ay1 * (this.a1y2 + this.a2y2) + this.az1 * (this.a1z2 + this.a2z2);
  95436. this.k02 = this.ax1 * (this.a1x3 + this.a2x3) + this.ay1 * (this.a1y3 + this.a2y3) + this.az1 * (this.a1z3 + this.a2z3);
  95437. this.k10 = this.ax2 * (this.a1x1 + this.a2x1) + this.ay2 * (this.a1y1 + this.a2y1) + this.az2 * (this.a1z1 + this.a2z1);
  95438. this.k11 = this.ax2 * (this.a1x2 + this.a2x2) + this.ay2 * (this.a1y2 + this.a2y2) + this.az2 * (this.a1z2 + this.a2z2);
  95439. this.k12 = this.ax2 * (this.a1x3 + this.a2x3) + this.ay2 * (this.a1y3 + this.a2y3) + this.az2 * (this.a1z3 + this.a2z3);
  95440. this.k20 = this.ax3 * (this.a1x1 + this.a2x1) + this.ay3 * (this.a1y1 + this.a2y1) + this.az3 * (this.a1z1 + this.a2z1);
  95441. this.k21 = this.ax3 * (this.a1x2 + this.a2x2) + this.ay3 * (this.a1y2 + this.a2y2) + this.az3 * (this.a1z2 + this.a2z2);
  95442. this.k22 = this.ax3 * (this.a1x3 + this.a2x3) + this.ay3 * (this.a1y3 + this.a2y3) + this.az3 * (this.a1z3 + this.a2z3);
  95443. this.kv00 = this.k00;
  95444. this.kv11 = this.k11;
  95445. this.kv22 = this.k22;
  95446. this.dv00 = 1 / this.kv00;
  95447. this.dv11 = 1 / this.kv11;
  95448. this.dv22 = 1 / this.kv22;
  95449. if (enableSpring1 && this.limitState1 != 2) {
  95450. var omega = 6.2831853 * frequency1;
  95451. var k = omega * omega * timeStep;
  95452. var dmp = invTimeStep / (k + 2 * this.limitMotor1.dampingRatio * omega);
  95453. this.cfm1 = this.kv00 * dmp;
  95454. this.limitVelocity1 *= k * dmp;
  95455. } else {
  95456. this.cfm1 = 0;
  95457. this.limitVelocity1 *= invTimeStep * 0.05;
  95458. }
  95459. if (enableSpring2 && this.limitState2 != 2) {
  95460. omega = 6.2831853 * frequency2;
  95461. k = omega * omega * timeStep;
  95462. dmp = invTimeStep / (k + 2 * this.limitMotor2.dampingRatio * omega);
  95463. this.cfm2 = this.kv11 * dmp;
  95464. this.limitVelocity2 *= k * dmp;
  95465. } else {
  95466. this.cfm2 = 0;
  95467. this.limitVelocity2 *= invTimeStep * 0.05;
  95468. }
  95469. if (enableSpring3 && this.limitState3 != 2) {
  95470. omega = 6.2831853 * frequency3;
  95471. k = omega * omega * timeStep;
  95472. dmp = invTimeStep / (k + 2 * this.limitMotor3.dampingRatio * omega);
  95473. this.cfm3 = this.kv22 * dmp;
  95474. this.limitVelocity3 *= k * dmp;
  95475. } else {
  95476. this.cfm3 = 0;
  95477. this.limitVelocity3 *= invTimeStep * 0.05;
  95478. }
  95479. this.k00 += this.cfm1;
  95480. this.k11 += this.cfm2;
  95481. this.k22 += this.cfm3;
  95482. var inv = 1 / (
  95483. this.k00 * (this.k11 * this.k22 - this.k21 * this.k12) +
  95484. this.k10 * (this.k21 * this.k02 - this.k01 * this.k22) +
  95485. this.k20 * (this.k01 * this.k12 - this.k11 * this.k02)
  95486. );
  95487. this.d00 = (this.k11 * this.k22 - this.k12 * this.k21) * inv;
  95488. this.d01 = (this.k02 * this.k21 - this.k01 * this.k22) * inv;
  95489. this.d02 = (this.k01 * this.k12 - this.k02 * this.k11) * inv;
  95490. this.d10 = (this.k12 * this.k20 - this.k10 * this.k22) * inv;
  95491. this.d11 = (this.k00 * this.k22 - this.k02 * this.k20) * inv;
  95492. this.d12 = (this.k02 * this.k10 - this.k00 * this.k12) * inv;
  95493. this.d20 = (this.k10 * this.k21 - this.k11 * this.k20) * inv;
  95494. this.d21 = (this.k01 * this.k20 - this.k00 * this.k21) * inv;
  95495. this.d22 = (this.k00 * this.k11 - this.k01 * this.k10) * inv;
  95496. this.limitImpulse1 *= 0.95;
  95497. this.motorImpulse1 *= 0.95;
  95498. this.limitImpulse2 *= 0.95;
  95499. this.motorImpulse2 *= 0.95;
  95500. this.limitImpulse3 *= 0.95;
  95501. this.motorImpulse3 *= 0.95;
  95502. var totalImpulse1 = this.limitImpulse1 + this.motorImpulse1;
  95503. var totalImpulse2 = this.limitImpulse2 + this.motorImpulse2;
  95504. var totalImpulse3 = this.limitImpulse3 + this.motorImpulse3;
  95505. this.a1.x += totalImpulse1 * this.a1x1 + totalImpulse2 * this.a1x2 + totalImpulse3 * this.a1x3;
  95506. this.a1.y += totalImpulse1 * this.a1y1 + totalImpulse2 * this.a1y2 + totalImpulse3 * this.a1y3;
  95507. this.a1.z += totalImpulse1 * this.a1z1 + totalImpulse2 * this.a1z2 + totalImpulse3 * this.a1z3;
  95508. this.a2.x -= totalImpulse1 * this.a2x1 + totalImpulse2 * this.a2x2 + totalImpulse3 * this.a2x3;
  95509. this.a2.y -= totalImpulse1 * this.a2y1 + totalImpulse2 * this.a2y2 + totalImpulse3 * this.a2y3;
  95510. this.a2.z -= totalImpulse1 * this.a2z1 + totalImpulse2 * this.a2z2 + totalImpulse3 * this.a2z3;
  95511. },
  95512. solve_: function () {
  95513. var rvx = this.a2.x - this.a1.x;
  95514. var rvy = this.a2.y - this.a1.y;
  95515. var rvz = this.a2.z - this.a1.z;
  95516. this.limitVelocity3 = 30;
  95517. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1 - this.limitVelocity1;
  95518. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2 - this.limitVelocity2;
  95519. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3 - this.limitVelocity3;
  95520. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  95521. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  95522. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  95523. this.limitImpulse1 += dLimitImpulse1;
  95524. this.limitImpulse2 += dLimitImpulse2;
  95525. this.limitImpulse3 += dLimitImpulse3;
  95526. this.a1.x += dLimitImpulse1 * this.a1x1 + dLimitImpulse2 * this.a1x2 + dLimitImpulse3 * this.a1x3;
  95527. this.a1.y += dLimitImpulse1 * this.a1y1 + dLimitImpulse2 * this.a1y2 + dLimitImpulse3 * this.a1y3;
  95528. this.a1.z += dLimitImpulse1 * this.a1z1 + dLimitImpulse2 * this.a1z2 + dLimitImpulse3 * this.a1z3;
  95529. this.a2.x -= dLimitImpulse1 * this.a2x1 + dLimitImpulse2 * this.a2x2 + dLimitImpulse3 * this.a2x3;
  95530. this.a2.y -= dLimitImpulse1 * this.a2y1 + dLimitImpulse2 * this.a2y2 + dLimitImpulse3 * this.a2y3;
  95531. this.a2.z -= dLimitImpulse1 * this.a2z1 + dLimitImpulse2 * this.a2z2 + dLimitImpulse3 * this.a2z3;
  95532. },
  95533. solve: function () {
  95534. var rvx = this.a2.x - this.a1.x;
  95535. var rvy = this.a2.y - this.a1.y;
  95536. var rvz = this.a2.z - this.a1.z;
  95537. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1;
  95538. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  95539. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3;
  95540. var oldMotorImpulse1 = this.motorImpulse1;
  95541. var oldMotorImpulse2 = this.motorImpulse2;
  95542. var oldMotorImpulse3 = this.motorImpulse3;
  95543. var dMotorImpulse1 = 0;
  95544. var dMotorImpulse2 = 0;
  95545. var dMotorImpulse3 = 0;
  95546. if (this.enableMotor1) {
  95547. dMotorImpulse1 = (rvn1 - this.motorSpeed1) * this.dv00;
  95548. this.motorImpulse1 += dMotorImpulse1;
  95549. if (this.motorImpulse1 > this.maxMotorImpulse1) { // clamp motor impulse
  95550. this.motorImpulse1 = this.maxMotorImpulse1;
  95551. } else if (this.motorImpulse1 < -this.maxMotorImpulse1) {
  95552. this.motorImpulse1 = -this.maxMotorImpulse1;
  95553. }
  95554. dMotorImpulse1 = this.motorImpulse1 - oldMotorImpulse1;
  95555. }
  95556. if (this.enableMotor2) {
  95557. dMotorImpulse2 = (rvn2 - this.motorSpeed2) * this.dv11;
  95558. this.motorImpulse2 += dMotorImpulse2;
  95559. if (this.motorImpulse2 > this.maxMotorImpulse2) { // clamp motor impulse
  95560. this.motorImpulse2 = this.maxMotorImpulse2;
  95561. } else if (this.motorImpulse2 < -this.maxMotorImpulse2) {
  95562. this.motorImpulse2 = -this.maxMotorImpulse2;
  95563. }
  95564. dMotorImpulse2 = this.motorImpulse2 - oldMotorImpulse2;
  95565. }
  95566. if (this.enableMotor3) {
  95567. dMotorImpulse3 = (rvn3 - this.motorSpeed3) * this.dv22;
  95568. this.motorImpulse3 += dMotorImpulse3;
  95569. if (this.motorImpulse3 > this.maxMotorImpulse3) { // clamp motor impulse
  95570. this.motorImpulse3 = this.maxMotorImpulse3;
  95571. } else if (this.motorImpulse3 < -this.maxMotorImpulse3) {
  95572. this.motorImpulse3 = -this.maxMotorImpulse3;
  95573. }
  95574. dMotorImpulse3 = this.motorImpulse3 - oldMotorImpulse3;
  95575. }
  95576. // apply motor impulse to relative velocity
  95577. rvn1 += dMotorImpulse1 * this.kv00 + dMotorImpulse2 * this.k01 + dMotorImpulse3 * this.k02;
  95578. rvn2 += dMotorImpulse1 * this.k10 + dMotorImpulse2 * this.kv11 + dMotorImpulse3 * this.k12;
  95579. rvn3 += dMotorImpulse1 * this.k20 + dMotorImpulse2 * this.k21 + dMotorImpulse3 * this.kv22;
  95580. // subtract target velocity and applied impulse
  95581. rvn1 -= this.limitVelocity1 + this.limitImpulse1 * this.cfm1;
  95582. rvn2 -= this.limitVelocity2 + this.limitImpulse2 * this.cfm2;
  95583. rvn3 -= this.limitVelocity3 + this.limitImpulse3 * this.cfm3;
  95584. var oldLimitImpulse1 = this.limitImpulse1;
  95585. var oldLimitImpulse2 = this.limitImpulse2;
  95586. var oldLimitImpulse3 = this.limitImpulse3;
  95587. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  95588. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  95589. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  95590. this.limitImpulse1 += dLimitImpulse1;
  95591. this.limitImpulse2 += dLimitImpulse2;
  95592. this.limitImpulse3 += dLimitImpulse3;
  95593. // clamp
  95594. var clampState = 0;
  95595. if (this.limitState1 == 2 || this.limitImpulse1 * this.limitState1 < 0) {
  95596. dLimitImpulse1 = -oldLimitImpulse1;
  95597. rvn2 += dLimitImpulse1 * this.k10;
  95598. rvn3 += dLimitImpulse1 * this.k20;
  95599. clampState |= 1;
  95600. }
  95601. if (this.limitState2 == 2 || this.limitImpulse2 * this.limitState2 < 0) {
  95602. dLimitImpulse2 = -oldLimitImpulse2;
  95603. rvn1 += dLimitImpulse2 * this.k01;
  95604. rvn3 += dLimitImpulse2 * this.k21;
  95605. clampState |= 2;
  95606. }
  95607. if (this.limitState3 == 2 || this.limitImpulse3 * this.limitState3 < 0) {
  95608. dLimitImpulse3 = -oldLimitImpulse3;
  95609. rvn1 += dLimitImpulse3 * this.k02;
  95610. rvn2 += dLimitImpulse3 * this.k12;
  95611. clampState |= 4;
  95612. }
  95613. // update un-clamped impulse
  95614. // TODO: isolate division
  95615. var det;
  95616. switch (clampState) {
  95617. case 1: // update 2 3
  95618. det = 1 / (this.k11 * this.k22 - this.k12 * this.k21);
  95619. dLimitImpulse2 = (this.k22 * rvn2 + -this.k12 * rvn3) * det;
  95620. dLimitImpulse3 = (-this.k21 * rvn2 + this.k11 * rvn3) * det;
  95621. break;
  95622. case 2: // update 1 3
  95623. det = 1 / (this.k00 * this.k22 - this.k02 * this.k20);
  95624. dLimitImpulse1 = (this.k22 * rvn1 + -this.k02 * rvn3) * det;
  95625. dLimitImpulse3 = (-this.k20 * rvn1 + this.k00 * rvn3) * det;
  95626. break;
  95627. case 3: // update 3
  95628. dLimitImpulse3 = rvn3 / this.k22;
  95629. break;
  95630. case 4: // update 1 2
  95631. det = 1 / (this.k00 * this.k11 - this.k01 * this.k10);
  95632. dLimitImpulse1 = (this.k11 * rvn1 + -this.k01 * rvn2) * det;
  95633. dLimitImpulse2 = (-this.k10 * rvn1 + this.k00 * rvn2) * det;
  95634. break;
  95635. case 5: // update 2
  95636. dLimitImpulse2 = rvn2 / this.k11;
  95637. break;
  95638. case 6: // update 1
  95639. dLimitImpulse1 = rvn1 / this.k00;
  95640. break;
  95641. }
  95642. this.limitImpulse1 = dLimitImpulse1 + oldLimitImpulse1;
  95643. this.limitImpulse2 = dLimitImpulse2 + oldLimitImpulse2;
  95644. this.limitImpulse3 = dLimitImpulse3 + oldLimitImpulse3;
  95645. var dImpulse1 = dMotorImpulse1 + dLimitImpulse1;
  95646. var dImpulse2 = dMotorImpulse2 + dLimitImpulse2;
  95647. var dImpulse3 = dMotorImpulse3 + dLimitImpulse3;
  95648. // apply impulse
  95649. this.a1.x += dImpulse1 * this.a1x1 + dImpulse2 * this.a1x2 + dImpulse3 * this.a1x3;
  95650. this.a1.y += dImpulse1 * this.a1y1 + dImpulse2 * this.a1y2 + dImpulse3 * this.a1y3;
  95651. this.a1.z += dImpulse1 * this.a1z1 + dImpulse2 * this.a1z2 + dImpulse3 * this.a1z3;
  95652. this.a2.x -= dImpulse1 * this.a2x1 + dImpulse2 * this.a2x2 + dImpulse3 * this.a2x3;
  95653. this.a2.y -= dImpulse1 * this.a2y1 + dImpulse2 * this.a2y2 + dImpulse3 * this.a2y3;
  95654. this.a2.z -= dImpulse1 * this.a2z1 + dImpulse2 * this.a2z2 + dImpulse3 * this.a2z3;
  95655. rvx = this.a2.x - this.a1.x;
  95656. rvy = this.a2.y - this.a1.y;
  95657. rvz = this.a2.z - this.a1.z;
  95658. rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  95659. }
  95660. }
  95661. /**
  95662. * A rotational constraint for various joints.
  95663. * @author saharan
  95664. */
  95665. OIMO.RotationalConstraint = function (joint, limitMotor) {
  95666. this.cfm = NaN;
  95667. this.i1e00 = NaN;
  95668. this.i1e01 = NaN;
  95669. this.i1e02 = NaN;
  95670. this.i1e10 = NaN;
  95671. this.i1e11 = NaN;
  95672. this.i1e12 = NaN;
  95673. this.i1e20 = NaN;
  95674. this.i1e21 = NaN;
  95675. this.i1e22 = NaN;
  95676. this.i2e00 = NaN;
  95677. this.i2e01 = NaN;
  95678. this.i2e02 = NaN;
  95679. this.i2e10 = NaN;
  95680. this.i2e11 = NaN;
  95681. this.i2e12 = NaN;
  95682. this.i2e20 = NaN;
  95683. this.i2e21 = NaN;
  95684. this.i2e22 = NaN;
  95685. this.motorDenom = NaN;
  95686. this.invMotorDenom = NaN;
  95687. this.invDenom = NaN;
  95688. this.ax = NaN;
  95689. this.ay = NaN;
  95690. this.az = NaN;
  95691. this.a1x = NaN;
  95692. this.a1y = NaN;
  95693. this.a1z = NaN;
  95694. this.a2x = NaN;
  95695. this.a2y = NaN;
  95696. this.a2z = NaN;
  95697. this.enableLimit = false;
  95698. this.lowerLimit = NaN;
  95699. this.upperLimit = NaN;
  95700. this.limitVelocity = NaN;
  95701. this.limitState = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  95702. this.enableMotor = false;
  95703. this.motorSpeed = NaN;
  95704. this.maxMotorForce = NaN;
  95705. this.maxMotorImpulse = NaN;
  95706. this.limitMotor = limitMotor;
  95707. this.b1 = joint.body1;
  95708. this.b2 = joint.body2;
  95709. this.a1 = this.b1.angularVelocity;
  95710. this.a2 = this.b2.angularVelocity;
  95711. this.i1 = this.b1.inverseInertia;
  95712. this.i2 = this.b2.inverseInertia;
  95713. this.limitImpulse = 0;
  95714. this.motorImpulse = 0;
  95715. }
  95716. OIMO.RotationalConstraint.prototype = {
  95717. constructor: OIMO.RotationalConstraint,
  95718. preSolve: function (timeStep, invTimeStep) {
  95719. this.ax = this.limitMotor.axis.x;
  95720. this.ay = this.limitMotor.axis.y;
  95721. this.az = this.limitMotor.axis.z;
  95722. this.lowerLimit = this.limitMotor.lowerLimit;
  95723. this.upperLimit = this.limitMotor.upperLimit;
  95724. this.motorSpeed = this.limitMotor.motorSpeed;
  95725. this.maxMotorForce = this.limitMotor.maxMotorForce;
  95726. this.enableMotor = this.maxMotorForce > 0;
  95727. var ti1 = this.i1.elements;
  95728. var ti2 = this.i2.elements;
  95729. this.i1e00 = ti1[0];
  95730. this.i1e01 = ti1[1];
  95731. this.i1e02 = ti1[2];
  95732. this.i1e10 = ti1[3];
  95733. this.i1e11 = ti1[4];
  95734. this.i1e12 = ti1[5];
  95735. this.i1e20 = ti1[6];
  95736. this.i1e21 = ti1[7];
  95737. this.i1e22 = ti1[8];
  95738. this.i2e00 = ti2[0];
  95739. this.i2e01 = ti2[1];
  95740. this.i2e02 = ti2[2];
  95741. this.i2e10 = ti2[3];
  95742. this.i2e11 = ti2[4];
  95743. this.i2e12 = ti2[5];
  95744. this.i2e20 = ti2[6];
  95745. this.i2e21 = ti2[7];
  95746. this.i2e22 = ti2[8];
  95747. var frequency = this.limitMotor.frequency;
  95748. var enableSpring = frequency > 0;
  95749. var enableLimit = this.lowerLimit <= this.upperLimit;
  95750. var angle = this.limitMotor.angle;
  95751. if (enableLimit) {
  95752. if (this.lowerLimit == this.upperLimit) {
  95753. if (this.limitState != 0) {
  95754. this.limitState = 0;
  95755. this.limitImpulse = 0;
  95756. }
  95757. this.limitVelocity = this.lowerLimit - angle;
  95758. } else if (angle < this.lowerLimit) {
  95759. if (this.limitState != -1) {
  95760. this.limitState = -1;
  95761. this.limitImpulse = 0;
  95762. }
  95763. this.limitVelocity = this.lowerLimit - angle;
  95764. } else if (angle > this.upperLimit) {
  95765. if (this.limitState != 1) {
  95766. this.limitState = 1;
  95767. this.limitImpulse = 0;
  95768. }
  95769. this.limitVelocity = this.upperLimit - angle;
  95770. } else {
  95771. this.limitState = 2;
  95772. this.limitImpulse = 0;
  95773. this.limitVelocity = 0;
  95774. }
  95775. if (!enableSpring) {
  95776. if (this.limitVelocity > 0.02) this.limitVelocity -= 0.02;
  95777. else if (this.limitVelocity < -0.02) this.limitVelocity += 0.02;
  95778. else this.limitVelocity = 0;
  95779. }
  95780. } else {
  95781. this.limitState = 2;
  95782. this.limitImpulse = 0;
  95783. }
  95784. if (this.enableMotor && (this.limitState != 0 || enableSpring)) {
  95785. this.maxMotorImpulse = this.maxMotorForce * timeStep;
  95786. } else {
  95787. this.motorImpulse = 0;
  95788. this.maxMotorImpulse = 0;
  95789. }
  95790. this.a1x = this.ax * this.i1e00 + this.ay * this.i1e01 + this.az * this.i1e02;
  95791. this.a1y = this.ax * this.i1e10 + this.ay * this.i1e11 + this.az * this.i1e12;
  95792. this.a1z = this.ax * this.i1e20 + this.ay * this.i1e21 + this.az * this.i1e22;
  95793. this.a2x = this.ax * this.i2e00 + this.ay * this.i2e01 + this.az * this.i2e02;
  95794. this.a2y = this.ax * this.i2e10 + this.ay * this.i2e11 + this.az * this.i2e12;
  95795. this.a2z = this.ax * this.i2e20 + this.ay * this.i2e21 + this.az * this.i2e22;
  95796. this.motorDenom = this.ax * (this.a1x + this.a2x) + this.ay * (this.a1y + this.a2y) + this.az * (this.a1z + this.a2z);
  95797. this.invMotorDenom = 1 / this.motorDenom;
  95798. if (enableSpring && this.limitState != 2) {
  95799. var omega = 6.2831853 * frequency;
  95800. var k = omega * omega * timeStep;
  95801. var dmp = invTimeStep / (k + 2 * this.limitMotor.dampingRatio * omega);
  95802. this.cfm = this.motorDenom * dmp;
  95803. this.limitVelocity *= k * dmp;
  95804. } else {
  95805. this.cfm = 0;
  95806. this.limitVelocity *= invTimeStep * 0.05;
  95807. }
  95808. this.invDenom = 1 / (this.motorDenom + this.cfm);
  95809. this.limitImpulse *= 0.95;
  95810. this.motorImpulse *= 0.95;
  95811. var totalImpulse = this.limitImpulse + this.motorImpulse;
  95812. this.a1.x += totalImpulse * this.a1x;
  95813. this.a1.y += totalImpulse * this.a1y;
  95814. this.a1.z += totalImpulse * this.a1z;
  95815. this.a2.x -= totalImpulse * this.a2x;
  95816. this.a2.y -= totalImpulse * this.a2y;
  95817. this.a2.z -= totalImpulse * this.a2z;
  95818. },
  95819. solve: function () {
  95820. 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);
  95821. // motor part
  95822. var newMotorImpulse;
  95823. if (this.enableMotor) {
  95824. newMotorImpulse = (rvn - this.motorSpeed) * this.invMotorDenom;
  95825. var oldMotorImpulse = this.motorImpulse;
  95826. this.motorImpulse += newMotorImpulse;
  95827. if (this.motorImpulse > this.maxMotorImpulse) this.motorImpulse = this.maxMotorImpulse;
  95828. else if (this.motorImpulse < -this.maxMotorImpulse) this.motorImpulse = -this.maxMotorImpulse;
  95829. newMotorImpulse = this.motorImpulse - oldMotorImpulse;
  95830. rvn -= newMotorImpulse * this.motorDenom;
  95831. } else newMotorImpulse = 0;
  95832. // limit part
  95833. var newLimitImpulse;
  95834. if (this.limitState != 2) {
  95835. newLimitImpulse = (rvn - this.limitVelocity - this.limitImpulse * this.cfm) * this.invDenom;
  95836. var oldLimitImpulse = this.limitImpulse;
  95837. this.limitImpulse += newLimitImpulse;
  95838. if (this.limitImpulse * this.limitState < 0) this.limitImpulse = 0;
  95839. newLimitImpulse = this.limitImpulse - oldLimitImpulse;
  95840. } else newLimitImpulse = 0;
  95841. var totalImpulse = newLimitImpulse + newMotorImpulse;
  95842. this.a1.x += totalImpulse * this.a1x;
  95843. this.a1.y += totalImpulse * this.a1y;
  95844. this.a1.z += totalImpulse * this.a1z;
  95845. this.a2.x -= totalImpulse * this.a2x;
  95846. this.a2.y -= totalImpulse * this.a2y;
  95847. this.a2.z -= totalImpulse * this.a2z;
  95848. }
  95849. }
  95850. /**
  95851. * A three-axis translational constraint for various joints.
  95852. * @author saharan
  95853. */
  95854. OIMO.Translational3Constraint = function (joint, limitMotor1, limitMotor2, limitMotor3) {
  95855. this.m1 = NaN;
  95856. this.m2 = NaN;
  95857. this.i1e00 = NaN;
  95858. this.i1e01 = NaN;
  95859. this.i1e02 = NaN;
  95860. this.i1e10 = NaN;
  95861. this.i1e11 = NaN;
  95862. this.i1e12 = NaN;
  95863. this.i1e20 = NaN;
  95864. this.i1e21 = NaN;
  95865. this.i1e22 = NaN;
  95866. this.i2e00 = NaN;
  95867. this.i2e01 = NaN;
  95868. this.i2e02 = NaN;
  95869. this.i2e10 = NaN;
  95870. this.i2e11 = NaN;
  95871. this.i2e12 = NaN;
  95872. this.i2e20 = NaN;
  95873. this.i2e21 = NaN;
  95874. this.i2e22 = NaN;
  95875. this.ax1 = NaN;
  95876. this.ay1 = NaN;
  95877. this.az1 = NaN;
  95878. this.ax2 = NaN;
  95879. this.ay2 = NaN;
  95880. this.az2 = NaN;
  95881. this.ax3 = NaN;
  95882. this.ay3 = NaN;
  95883. this.az3 = NaN;
  95884. this.r1x = NaN;
  95885. this.r1y = NaN;
  95886. this.r1z = NaN;
  95887. this.r2x = NaN;
  95888. this.r2y = NaN;
  95889. this.r2z = NaN;
  95890. this.t1x1 = NaN;// jacobians
  95891. this.t1y1 = NaN;
  95892. this.t1z1 = NaN;
  95893. this.t2x1 = NaN;
  95894. this.t2y1 = NaN;
  95895. this.t2z1 = NaN;
  95896. this.l1x1 = NaN;
  95897. this.l1y1 = NaN;
  95898. this.l1z1 = NaN;
  95899. this.l2x1 = NaN;
  95900. this.l2y1 = NaN;
  95901. this.l2z1 = NaN;
  95902. this.a1x1 = NaN;
  95903. this.a1y1 = NaN;
  95904. this.a1z1 = NaN;
  95905. this.a2x1 = NaN;
  95906. this.a2y1 = NaN;
  95907. this.a2z1 = NaN;
  95908. this.t1x2 = NaN;
  95909. this.t1y2 = NaN;
  95910. this.t1z2 = NaN;
  95911. this.t2x2 = NaN;
  95912. this.t2y2 = NaN;
  95913. this.t2z2 = NaN;
  95914. this.l1x2 = NaN;
  95915. this.l1y2 = NaN;
  95916. this.l1z2 = NaN;
  95917. this.l2x2 = NaN;
  95918. this.l2y2 = NaN;
  95919. this.l2z2 = NaN;
  95920. this.a1x2 = NaN;
  95921. this.a1y2 = NaN;
  95922. this.a1z2 = NaN;
  95923. this.a2x2 = NaN;
  95924. this.a2y2 = NaN;
  95925. this.a2z2 = NaN;
  95926. this.t1x3 = NaN;
  95927. this.t1y3 = NaN;
  95928. this.t1z3 = NaN;
  95929. this.t2x3 = NaN;
  95930. this.t2y3 = NaN;
  95931. this.t2z3 = NaN;
  95932. this.l1x3 = NaN;
  95933. this.l1y3 = NaN;
  95934. this.l1z3 = NaN;
  95935. this.l2x3 = NaN;
  95936. this.l2y3 = NaN;
  95937. this.l2z3 = NaN;
  95938. this.a1x3 = NaN;
  95939. this.a1y3 = NaN;
  95940. this.a1z3 = NaN;
  95941. this.a2x3 = NaN;
  95942. this.a2y3 = NaN;
  95943. this.a2z3 = NaN;
  95944. this.lowerLimit1 = NaN;
  95945. this.upperLimit1 = NaN;
  95946. this.limitVelocity1 = NaN;
  95947. this.limitState1 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  95948. this.enableMotor1 = false;
  95949. this.motorSpeed1 = NaN;
  95950. this.maxMotorForce1 = NaN;
  95951. this.maxMotorImpulse1 = NaN;
  95952. this.lowerLimit2 = NaN;
  95953. this.upperLimit2 = NaN;
  95954. this.limitVelocity2 = NaN;
  95955. this.limitState2 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  95956. this.enableMotor2 = false;
  95957. this.motorSpeed2 = NaN;
  95958. this.maxMotorForce2 = NaN;
  95959. this.maxMotorImpulse2 = NaN;
  95960. this.lowerLimit3 = NaN;
  95961. this.upperLimit3 = NaN;
  95962. this.limitVelocity3 = NaN;
  95963. this.limitState3 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  95964. this.enableMotor3 = false;
  95965. this.motorSpeed3 = NaN;
  95966. this.maxMotorForce3 = NaN;
  95967. this.maxMotorImpulse3 = NaN;
  95968. this.k00 = NaN; // K = J*M*JT
  95969. this.k01 = NaN;
  95970. this.k02 = NaN;
  95971. this.k10 = NaN;
  95972. this.k11 = NaN;
  95973. this.k12 = NaN;
  95974. this.k20 = NaN;
  95975. this.k21 = NaN;
  95976. this.k22 = NaN;
  95977. this.kv00 = NaN; // diagonals without CFMs
  95978. this.kv11 = NaN;
  95979. this.kv22 = NaN;
  95980. this.dv00 = NaN; // ...inverted
  95981. this.dv11 = NaN;
  95982. this.dv22 = NaN;
  95983. this.d00 = NaN; // K^-1
  95984. this.d01 = NaN;
  95985. this.d02 = NaN;
  95986. this.d10 = NaN;
  95987. this.d11 = NaN;
  95988. this.d12 = NaN;
  95989. this.d20 = NaN;
  95990. this.d21 = NaN;
  95991. this.d22 = NaN;
  95992. this.limitMotor1 = limitMotor1;
  95993. this.limitMotor2 = limitMotor2;
  95994. this.limitMotor3 = limitMotor3;
  95995. this.b1 = joint.body1;
  95996. this.b2 = joint.body2;
  95997. this.p1 = joint.anchorPoint1;
  95998. this.p2 = joint.anchorPoint2;
  95999. this.r1 = joint.relativeAnchorPoint1;
  96000. this.r2 = joint.relativeAnchorPoint2;
  96001. this.l1 = this.b1.linearVelocity;
  96002. this.l2 = this.b2.linearVelocity;
  96003. this.a1 = this.b1.angularVelocity;
  96004. this.a2 = this.b2.angularVelocity;
  96005. this.i1 = this.b1.inverseInertia;
  96006. this.i2 = this.b2.inverseInertia;
  96007. this.limitImpulse1 = 0;
  96008. this.motorImpulse1 = 0;
  96009. this.limitImpulse2 = 0;
  96010. this.motorImpulse2 = 0;
  96011. this.limitImpulse3 = 0;
  96012. this.motorImpulse3 = 0;
  96013. this.cfm1 = 0;// Constraint Force Mixing
  96014. this.cfm2 = 0;
  96015. this.cfm3 = 0;
  96016. this.weight = -1;
  96017. }
  96018. OIMO.Translational3Constraint.prototype = {
  96019. constructor: OIMO.Translational3Constraint,
  96020. preSolve: function (timeStep, invTimeStep) {
  96021. this.ax1 = this.limitMotor1.axis.x;
  96022. this.ay1 = this.limitMotor1.axis.y;
  96023. this.az1 = this.limitMotor1.axis.z;
  96024. this.ax2 = this.limitMotor2.axis.x;
  96025. this.ay2 = this.limitMotor2.axis.y;
  96026. this.az2 = this.limitMotor2.axis.z;
  96027. this.ax3 = this.limitMotor3.axis.x;
  96028. this.ay3 = this.limitMotor3.axis.y;
  96029. this.az3 = this.limitMotor3.axis.z;
  96030. this.lowerLimit1 = this.limitMotor1.lowerLimit;
  96031. this.upperLimit1 = this.limitMotor1.upperLimit;
  96032. this.motorSpeed1 = this.limitMotor1.motorSpeed;
  96033. this.maxMotorForce1 = this.limitMotor1.maxMotorForce;
  96034. this.enableMotor1 = this.maxMotorForce1 > 0;
  96035. this.lowerLimit2 = this.limitMotor2.lowerLimit;
  96036. this.upperLimit2 = this.limitMotor2.upperLimit;
  96037. this.motorSpeed2 = this.limitMotor2.motorSpeed;
  96038. this.maxMotorForce2 = this.limitMotor2.maxMotorForce;
  96039. this.enableMotor2 = this.maxMotorForce2 > 0;
  96040. this.lowerLimit3 = this.limitMotor3.lowerLimit;
  96041. this.upperLimit3 = this.limitMotor3.upperLimit;
  96042. this.motorSpeed3 = this.limitMotor3.motorSpeed;
  96043. this.maxMotorForce3 = this.limitMotor3.maxMotorForce;
  96044. this.enableMotor3 = this.maxMotorForce3 > 0;
  96045. this.m1 = this.b1.inverseMass;
  96046. this.m2 = this.b2.inverseMass;
  96047. var ti1 = this.i1.elements;
  96048. var ti2 = this.i2.elements;
  96049. this.i1e00 = ti1[0];
  96050. this.i1e01 = ti1[1];
  96051. this.i1e02 = ti1[2];
  96052. this.i1e10 = ti1[3];
  96053. this.i1e11 = ti1[4];
  96054. this.i1e12 = ti1[5];
  96055. this.i1e20 = ti1[6];
  96056. this.i1e21 = ti1[7];
  96057. this.i1e22 = ti1[8];
  96058. this.i2e00 = ti2[0];
  96059. this.i2e01 = ti2[1];
  96060. this.i2e02 = ti2[2];
  96061. this.i2e10 = ti2[3];
  96062. this.i2e11 = ti2[4];
  96063. this.i2e12 = ti2[5];
  96064. this.i2e20 = ti2[6];
  96065. this.i2e21 = ti2[7];
  96066. this.i2e22 = ti2[8];
  96067. var dx = this.p2.x - this.p1.x;
  96068. var dy = this.p2.y - this.p1.y;
  96069. var dz = this.p2.z - this.p1.z;
  96070. var d1 = dx * this.ax1 + dy * this.ay1 + dz * this.az1;
  96071. var d2 = dx * this.ax2 + dy * this.ay2 + dz * this.az2;
  96072. var d3 = dx * this.ax3 + dy * this.ay3 + dz * this.az3;
  96073. var frequency1 = this.limitMotor1.frequency;
  96074. var frequency2 = this.limitMotor2.frequency;
  96075. var frequency3 = this.limitMotor3.frequency;
  96076. var enableSpring1 = frequency1 > 0;
  96077. var enableSpring2 = frequency2 > 0;
  96078. var enableSpring3 = frequency3 > 0;
  96079. var enableLimit1 = this.lowerLimit1 <= this.upperLimit1;
  96080. var enableLimit2 = this.lowerLimit2 <= this.upperLimit2;
  96081. var enableLimit3 = this.lowerLimit3 <= this.upperLimit3;
  96082. // for stability
  96083. if (enableSpring1 && d1 > 20 || d1 < -20) {
  96084. enableSpring1 = false;
  96085. }
  96086. if (enableSpring2 && d2 > 20 || d2 < -20) {
  96087. enableSpring2 = false;
  96088. }
  96089. if (enableSpring3 && d3 > 20 || d3 < -20) {
  96090. enableSpring3 = false;
  96091. }
  96092. if (enableLimit1) {
  96093. if (this.lowerLimit1 == this.upperLimit1) {
  96094. if (this.limitState1 != 0) {
  96095. this.limitState1 = 0;
  96096. this.limitImpulse1 = 0;
  96097. }
  96098. this.limitVelocity1 = this.lowerLimit1 - d1;
  96099. if (!enableSpring1) d1 = this.lowerLimit1;
  96100. } else if (d1 < this.lowerLimit1) {
  96101. if (this.limitState1 != -1) {
  96102. this.limitState1 = -1;
  96103. this.limitImpulse1 = 0;
  96104. }
  96105. this.limitVelocity1 = this.lowerLimit1 - d1;
  96106. if (!enableSpring1) d1 = this.lowerLimit1;
  96107. } else if (d1 > this.upperLimit1) {
  96108. if (this.limitState1 != 1) {
  96109. this.limitState1 = 1;
  96110. this.limitImpulse1 = 0;
  96111. }
  96112. this.limitVelocity1 = this.upperLimit1 - d1;
  96113. if (!enableSpring1) d1 = this.upperLimit1;
  96114. } else {
  96115. this.limitState1 = 2;
  96116. this.limitImpulse1 = 0;
  96117. this.limitVelocity1 = 0;
  96118. }
  96119. if (!enableSpring1) {
  96120. if (this.limitVelocity1 > 0.005) this.limitVelocity1 -= 0.005;
  96121. else if (this.limitVelocity1 < -0.005) this.limitVelocity1 += 0.005;
  96122. else this.limitVelocity1 = 0;
  96123. }
  96124. } else {
  96125. this.limitState1 = 2;
  96126. this.limitImpulse1 = 0;
  96127. }
  96128. if (enableLimit2) {
  96129. if (this.lowerLimit2 == this.upperLimit2) {
  96130. if (this.limitState2 != 0) {
  96131. this.limitState2 = 0;
  96132. this.limitImpulse2 = 0;
  96133. }
  96134. this.limitVelocity2 = this.lowerLimit2 - d2;
  96135. if (!enableSpring2) d2 = this.lowerLimit2;
  96136. } else if (d2 < this.lowerLimit2) {
  96137. if (this.limitState2 != -1) {
  96138. this.limitState2 = -1;
  96139. this.limitImpulse2 = 0;
  96140. }
  96141. this.limitVelocity2 = this.lowerLimit2 - d2;
  96142. if (!enableSpring2) d2 = this.lowerLimit2;
  96143. } else if (d2 > this.upperLimit2) {
  96144. if (this.limitState2 != 1) {
  96145. this.limitState2 = 1;
  96146. this.limitImpulse2 = 0;
  96147. }
  96148. this.limitVelocity2 = this.upperLimit2 - d2;
  96149. if (!enableSpring2) d2 = this.upperLimit2;
  96150. } else {
  96151. this.limitState2 = 2;
  96152. this.limitImpulse2 = 0;
  96153. this.limitVelocity2 = 0;
  96154. }
  96155. if (!enableSpring2) {
  96156. if (this.limitVelocity2 > 0.005) this.limitVelocity2 -= 0.005;
  96157. else if (this.limitVelocity2 < -0.005) this.limitVelocity2 += 0.005;
  96158. else this.limitVelocity2 = 0;
  96159. }
  96160. } else {
  96161. this.limitState2 = 2;
  96162. this.limitImpulse2 = 0;
  96163. }
  96164. if (enableLimit3) {
  96165. if (this.lowerLimit3 == this.upperLimit3) {
  96166. if (this.limitState3 != 0) {
  96167. this.limitState3 = 0;
  96168. this.limitImpulse3 = 0;
  96169. }
  96170. this.limitVelocity3 = this.lowerLimit3 - d3;
  96171. if (!enableSpring3) d3 = this.lowerLimit3;
  96172. } else if (d3 < this.lowerLimit3) {
  96173. if (this.limitState3 != -1) {
  96174. this.limitState3 = -1;
  96175. this.limitImpulse3 = 0;
  96176. }
  96177. this.limitVelocity3 = this.lowerLimit3 - d3;
  96178. if (!enableSpring3) d3 = this.lowerLimit3;
  96179. } else if (d3 > this.upperLimit3) {
  96180. if (this.limitState3 != 1) {
  96181. this.limitState3 = 1;
  96182. this.limitImpulse3 = 0;
  96183. }
  96184. this.limitVelocity3 = this.upperLimit3 - d3;
  96185. if (!enableSpring3) d3 = this.upperLimit3;
  96186. } else {
  96187. this.limitState3 = 2;
  96188. this.limitImpulse3 = 0;
  96189. this.limitVelocity3 = 0;
  96190. }
  96191. if (!enableSpring3) {
  96192. if (this.limitVelocity3 > 0.005) this.limitVelocity3 -= 0.005;
  96193. else if (this.limitVelocity3 < -0.005) this.limitVelocity3 += 0.005;
  96194. else this.limitVelocity3 = 0;
  96195. }
  96196. } else {
  96197. this.limitState3 = 2;
  96198. this.limitImpulse3 = 0;
  96199. }
  96200. if (this.enableMotor1 && (this.limitState1 != 0 || enableSpring1)) {
  96201. this.maxMotorImpulse1 = this.maxMotorForce1 * timeStep;
  96202. } else {
  96203. this.motorImpulse1 = 0;
  96204. this.maxMotorImpulse1 = 0;
  96205. }
  96206. if (this.enableMotor2 && (this.limitState2 != 0 || enableSpring2)) {
  96207. this.maxMotorImpulse2 = this.maxMotorForce2 * timeStep;
  96208. } else {
  96209. this.motorImpulse2 = 0;
  96210. this.maxMotorImpulse2 = 0;
  96211. }
  96212. if (this.enableMotor3 && (this.limitState3 != 0 || enableSpring3)) {
  96213. this.maxMotorImpulse3 = this.maxMotorForce3 * timeStep;
  96214. } else {
  96215. this.motorImpulse3 = 0;
  96216. this.maxMotorImpulse3 = 0;
  96217. }
  96218. var rdx = d1 * this.ax1 + d2 * this.ax2 + d3 * this.ax2;
  96219. var rdy = d1 * this.ay1 + d2 * this.ay2 + d3 * this.ay2;
  96220. var rdz = d1 * this.az1 + d2 * this.az2 + d3 * this.az2;
  96221. var w1 = this.m2 / (this.m1 + this.m2);
  96222. if (this.weight >= 0) w1 = this.weight; // use given weight
  96223. var w2 = 1 - w1;
  96224. this.r1x = this.r1.x + rdx * w1;
  96225. this.r1y = this.r1.y + rdy * w1;
  96226. this.r1z = this.r1.z + rdz * w1;
  96227. this.r2x = this.r2.x - rdx * w2;
  96228. this.r2y = this.r2.y - rdy * w2;
  96229. this.r2z = this.r2.z - rdz * w2;
  96230. // build jacobians
  96231. this.t1x1 = this.r1y * this.az1 - this.r1z * this.ay1;
  96232. this.t1y1 = this.r1z * this.ax1 - this.r1x * this.az1;
  96233. this.t1z1 = this.r1x * this.ay1 - this.r1y * this.ax1;
  96234. this.t2x1 = this.r2y * this.az1 - this.r2z * this.ay1;
  96235. this.t2y1 = this.r2z * this.ax1 - this.r2x * this.az1;
  96236. this.t2z1 = this.r2x * this.ay1 - this.r2y * this.ax1;
  96237. this.l1x1 = this.ax1 * this.m1;
  96238. this.l1y1 = this.ay1 * this.m1;
  96239. this.l1z1 = this.az1 * this.m1;
  96240. this.l2x1 = this.ax1 * this.m2;
  96241. this.l2y1 = this.ay1 * this.m2;
  96242. this.l2z1 = this.az1 * this.m2;
  96243. this.a1x1 = this.t1x1 * this.i1e00 + this.t1y1 * this.i1e01 + this.t1z1 * this.i1e02;
  96244. this.a1y1 = this.t1x1 * this.i1e10 + this.t1y1 * this.i1e11 + this.t1z1 * this.i1e12;
  96245. this.a1z1 = this.t1x1 * this.i1e20 + this.t1y1 * this.i1e21 + this.t1z1 * this.i1e22;
  96246. this.a2x1 = this.t2x1 * this.i2e00 + this.t2y1 * this.i2e01 + this.t2z1 * this.i2e02;
  96247. this.a2y1 = this.t2x1 * this.i2e10 + this.t2y1 * this.i2e11 + this.t2z1 * this.i2e12;
  96248. this.a2z1 = this.t2x1 * this.i2e20 + this.t2y1 * this.i2e21 + this.t2z1 * this.i2e22;
  96249. this.t1x2 = this.r1y * this.az2 - this.r1z * this.ay2;
  96250. this.t1y2 = this.r1z * this.ax2 - this.r1x * this.az2;
  96251. this.t1z2 = this.r1x * this.ay2 - this.r1y * this.ax2;
  96252. this.t2x2 = this.r2y * this.az2 - this.r2z * this.ay2;
  96253. this.t2y2 = this.r2z * this.ax2 - this.r2x * this.az2;
  96254. this.t2z2 = this.r2x * this.ay2 - this.r2y * this.ax2;
  96255. this.l1x2 = this.ax2 * this.m1;
  96256. this.l1y2 = this.ay2 * this.m1;
  96257. this.l1z2 = this.az2 * this.m1;
  96258. this.l2x2 = this.ax2 * this.m2;
  96259. this.l2y2 = this.ay2 * this.m2;
  96260. this.l2z2 = this.az2 * this.m2;
  96261. this.a1x2 = this.t1x2 * this.i1e00 + this.t1y2 * this.i1e01 + this.t1z2 * this.i1e02;
  96262. this.a1y2 = this.t1x2 * this.i1e10 + this.t1y2 * this.i1e11 + this.t1z2 * this.i1e12;
  96263. this.a1z2 = this.t1x2 * this.i1e20 + this.t1y2 * this.i1e21 + this.t1z2 * this.i1e22;
  96264. this.a2x2 = this.t2x2 * this.i2e00 + this.t2y2 * this.i2e01 + this.t2z2 * this.i2e02;
  96265. this.a2y2 = this.t2x2 * this.i2e10 + this.t2y2 * this.i2e11 + this.t2z2 * this.i2e12;
  96266. this.a2z2 = this.t2x2 * this.i2e20 + this.t2y2 * this.i2e21 + this.t2z2 * this.i2e22;
  96267. this.t1x3 = this.r1y * this.az3 - this.r1z * this.ay3;
  96268. this.t1y3 = this.r1z * this.ax3 - this.r1x * this.az3;
  96269. this.t1z3 = this.r1x * this.ay3 - this.r1y * this.ax3;
  96270. this.t2x3 = this.r2y * this.az3 - this.r2z * this.ay3;
  96271. this.t2y3 = this.r2z * this.ax3 - this.r2x * this.az3;
  96272. this.t2z3 = this.r2x * this.ay3 - this.r2y * this.ax3;
  96273. this.l1x3 = this.ax3 * this.m1;
  96274. this.l1y3 = this.ay3 * this.m1;
  96275. this.l1z3 = this.az3 * this.m1;
  96276. this.l2x3 = this.ax3 * this.m2;
  96277. this.l2y3 = this.ay3 * this.m2;
  96278. this.l2z3 = this.az3 * this.m2;
  96279. this.a1x3 = this.t1x3 * this.i1e00 + this.t1y3 * this.i1e01 + this.t1z3 * this.i1e02;
  96280. this.a1y3 = this.t1x3 * this.i1e10 + this.t1y3 * this.i1e11 + this.t1z3 * this.i1e12;
  96281. this.a1z3 = this.t1x3 * this.i1e20 + this.t1y3 * this.i1e21 + this.t1z3 * this.i1e22;
  96282. this.a2x3 = this.t2x3 * this.i2e00 + this.t2y3 * this.i2e01 + this.t2z3 * this.i2e02;
  96283. this.a2y3 = this.t2x3 * this.i2e10 + this.t2y3 * this.i2e11 + this.t2z3 * this.i2e12;
  96284. this.a2z3 = this.t2x3 * this.i2e20 + this.t2y3 * this.i2e21 + this.t2z3 * this.i2e22;
  96285. // build an impulse matrix
  96286. var m12 = this.m1 + this.m2;
  96287. this.k00 = (this.ax1 * this.ax1 + this.ay1 * this.ay1 + this.az1 * this.az1) * m12;
  96288. this.k01 = (this.ax1 * this.ax2 + this.ay1 * this.ay2 + this.az1 * this.az2) * m12;
  96289. this.k02 = (this.ax1 * this.ax3 + this.ay1 * this.ay3 + this.az1 * this.az3) * m12;
  96290. this.k10 = (this.ax2 * this.ax1 + this.ay2 * this.ay1 + this.az2 * this.az1) * m12;
  96291. this.k11 = (this.ax2 * this.ax2 + this.ay2 * this.ay2 + this.az2 * this.az2) * m12;
  96292. this.k12 = (this.ax2 * this.ax3 + this.ay2 * this.ay3 + this.az2 * this.az3) * m12;
  96293. this.k20 = (this.ax3 * this.ax1 + this.ay3 * this.ay1 + this.az3 * this.az1) * m12;
  96294. this.k21 = (this.ax3 * this.ax2 + this.ay3 * this.ay2 + this.az3 * this.az2) * m12;
  96295. this.k22 = (this.ax3 * this.ax3 + this.ay3 * this.ay3 + this.az3 * this.az3) * m12;
  96296. this.k00 += this.t1x1 * this.a1x1 + this.t1y1 * this.a1y1 + this.t1z1 * this.a1z1;
  96297. this.k01 += this.t1x1 * this.a1x2 + this.t1y1 * this.a1y2 + this.t1z1 * this.a1z2;
  96298. this.k02 += this.t1x1 * this.a1x3 + this.t1y1 * this.a1y3 + this.t1z1 * this.a1z3;
  96299. this.k10 += this.t1x2 * this.a1x1 + this.t1y2 * this.a1y1 + this.t1z2 * this.a1z1;
  96300. this.k11 += this.t1x2 * this.a1x2 + this.t1y2 * this.a1y2 + this.t1z2 * this.a1z2;
  96301. this.k12 += this.t1x2 * this.a1x3 + this.t1y2 * this.a1y3 + this.t1z2 * this.a1z3;
  96302. this.k20 += this.t1x3 * this.a1x1 + this.t1y3 * this.a1y1 + this.t1z3 * this.a1z1;
  96303. this.k21 += this.t1x3 * this.a1x2 + this.t1y3 * this.a1y2 + this.t1z3 * this.a1z2;
  96304. this.k22 += this.t1x3 * this.a1x3 + this.t1y3 * this.a1y3 + this.t1z3 * this.a1z3;
  96305. this.k00 += this.t2x1 * this.a2x1 + this.t2y1 * this.a2y1 + this.t2z1 * this.a2z1;
  96306. this.k01 += this.t2x1 * this.a2x2 + this.t2y1 * this.a2y2 + this.t2z1 * this.a2z2;
  96307. this.k02 += this.t2x1 * this.a2x3 + this.t2y1 * this.a2y3 + this.t2z1 * this.a2z3;
  96308. this.k10 += this.t2x2 * this.a2x1 + this.t2y2 * this.a2y1 + this.t2z2 * this.a2z1;
  96309. this.k11 += this.t2x2 * this.a2x2 + this.t2y2 * this.a2y2 + this.t2z2 * this.a2z2;
  96310. this.k12 += this.t2x2 * this.a2x3 + this.t2y2 * this.a2y3 + this.t2z2 * this.a2z3;
  96311. this.k20 += this.t2x3 * this.a2x1 + this.t2y3 * this.a2y1 + this.t2z3 * this.a2z1;
  96312. this.k21 += this.t2x3 * this.a2x2 + this.t2y3 * this.a2y2 + this.t2z3 * this.a2z2;
  96313. this.k22 += this.t2x3 * this.a2x3 + this.t2y3 * this.a2y3 + this.t2z3 * this.a2z3;
  96314. this.kv00 = this.k00;
  96315. this.kv11 = this.k11;
  96316. this.kv22 = this.k22;
  96317. this.dv00 = 1 / this.kv00;
  96318. this.dv11 = 1 / this.kv11;
  96319. this.dv22 = 1 / this.kv22;
  96320. if (enableSpring1 && this.limitState1 != 2) {
  96321. var omega = 6.2831853 * frequency1;
  96322. var k = omega * omega * timeStep;
  96323. var dmp = invTimeStep / (k + 2 * this.limitMotor1.dampingRatio * omega);
  96324. this.cfm1 = this.kv00 * dmp;
  96325. this.limitVelocity1 *= k * dmp;
  96326. } else {
  96327. this.cfm1 = 0;
  96328. this.limitVelocity1 *= invTimeStep * 0.05;
  96329. }
  96330. if (enableSpring2 && this.limitState2 != 2) {
  96331. omega = 6.2831853 * frequency2;
  96332. k = omega * omega * timeStep;
  96333. dmp = invTimeStep / (k + 2 * this.limitMotor2.dampingRatio * omega);
  96334. this.cfm2 = this.kv11 * dmp;
  96335. this.limitVelocity2 *= k * dmp;
  96336. } else {
  96337. this.cfm2 = 0;
  96338. this.limitVelocity2 *= invTimeStep * 0.05;
  96339. }
  96340. if (enableSpring3 && this.limitState3 != 2) {
  96341. omega = 6.2831853 * frequency3;
  96342. k = omega * omega * timeStep;
  96343. dmp = invTimeStep / (k + 2 * this.limitMotor3.dampingRatio * omega);
  96344. this.cfm3 = this.kv22 * dmp;
  96345. this.limitVelocity3 *= k * dmp;
  96346. } else {
  96347. this.cfm3 = 0;
  96348. this.limitVelocity3 *= invTimeStep * 0.05;
  96349. }
  96350. this.k00 += this.cfm1;
  96351. this.k11 += this.cfm2;
  96352. this.k22 += this.cfm3;
  96353. var inv = 1 / (
  96354. this.k00 * (this.k11 * this.k22 - this.k21 * this.k12) +
  96355. this.k10 * (this.k21 * this.k02 - this.k01 * this.k22) +
  96356. this.k20 * (this.k01 * this.k12 - this.k11 * this.k02)
  96357. );
  96358. this.d00 = (this.k11 * this.k22 - this.k12 * this.k21) * inv;
  96359. this.d01 = (this.k02 * this.k21 - this.k01 * this.k22) * inv;
  96360. this.d02 = (this.k01 * this.k12 - this.k02 * this.k11) * inv;
  96361. this.d10 = (this.k12 * this.k20 - this.k10 * this.k22) * inv;
  96362. this.d11 = (this.k00 * this.k22 - this.k02 * this.k20) * inv;
  96363. this.d12 = (this.k02 * this.k10 - this.k00 * this.k12) * inv;
  96364. this.d20 = (this.k10 * this.k21 - this.k11 * this.k20) * inv;
  96365. this.d21 = (this.k01 * this.k20 - this.k00 * this.k21) * inv;
  96366. this.d22 = (this.k00 * this.k11 - this.k01 * this.k10) * inv;
  96367. // warm starting
  96368. var totalImpulse1 = this.limitImpulse1 + this.motorImpulse1;
  96369. var totalImpulse2 = this.limitImpulse2 + this.motorImpulse2;
  96370. var totalImpulse3 = this.limitImpulse3 + this.motorImpulse3;
  96371. this.l1.x += totalImpulse1 * this.l1x1 + totalImpulse2 * this.l1x2 + totalImpulse3 * this.l1x3;
  96372. this.l1.y += totalImpulse1 * this.l1y1 + totalImpulse2 * this.l1y2 + totalImpulse3 * this.l1y3;
  96373. this.l1.z += totalImpulse1 * this.l1z1 + totalImpulse2 * this.l1z2 + totalImpulse3 * this.l1z3;
  96374. this.a1.x += totalImpulse1 * this.a1x1 + totalImpulse2 * this.a1x2 + totalImpulse3 * this.a1x3;
  96375. this.a1.y += totalImpulse1 * this.a1y1 + totalImpulse2 * this.a1y2 + totalImpulse3 * this.a1y3;
  96376. this.a1.z += totalImpulse1 * this.a1z1 + totalImpulse2 * this.a1z2 + totalImpulse3 * this.a1z3;
  96377. this.l2.x -= totalImpulse1 * this.l2x1 + totalImpulse2 * this.l2x2 + totalImpulse3 * this.l2x3;
  96378. this.l2.y -= totalImpulse1 * this.l2y1 + totalImpulse2 * this.l2y2 + totalImpulse3 * this.l2y3;
  96379. this.l2.z -= totalImpulse1 * this.l2z1 + totalImpulse2 * this.l2z2 + totalImpulse3 * this.l2z3;
  96380. this.a2.x -= totalImpulse1 * this.a2x1 + totalImpulse2 * this.a2x2 + totalImpulse3 * this.a2x3;
  96381. this.a2.y -= totalImpulse1 * this.a2y1 + totalImpulse2 * this.a2y2 + totalImpulse3 * this.a2y3;
  96382. this.a2.z -= totalImpulse1 * this.a2z1 + totalImpulse2 * this.a2z2 + totalImpulse3 * this.a2z3;
  96383. },
  96384. solve: function () {
  96385. 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;
  96386. 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;
  96387. 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;
  96388. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1;
  96389. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  96390. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3;
  96391. var oldMotorImpulse1 = this.motorImpulse1;
  96392. var oldMotorImpulse2 = this.motorImpulse2;
  96393. var oldMotorImpulse3 = this.motorImpulse3;
  96394. var dMotorImpulse1 = 0;
  96395. var dMotorImpulse2 = 0;
  96396. var dMotorImpulse3 = 0;
  96397. if (this.enableMotor1) {
  96398. dMotorImpulse1 = (rvn1 - this.motorSpeed1) * this.dv00;
  96399. this.motorImpulse1 += dMotorImpulse1;
  96400. if (this.motorImpulse1 > this.maxMotorImpulse1) { // clamp motor impulse
  96401. this.motorImpulse1 = this.maxMotorImpulse1;
  96402. } else if (this.motorImpulse1 < -this.maxMotorImpulse1) {
  96403. this.motorImpulse1 = -this.maxMotorImpulse1;
  96404. }
  96405. dMotorImpulse1 = this.motorImpulse1 - oldMotorImpulse1;
  96406. }
  96407. if (this.enableMotor2) {
  96408. dMotorImpulse2 = (rvn2 - this.motorSpeed2) * this.dv11;
  96409. this.motorImpulse2 += dMotorImpulse2;
  96410. if (this.motorImpulse2 > this.maxMotorImpulse2) { // clamp motor impulse
  96411. this.motorImpulse2 = this.maxMotorImpulse2;
  96412. } else if (this.motorImpulse2 < -this.maxMotorImpulse2) {
  96413. this.motorImpulse2 = -this.maxMotorImpulse2;
  96414. }
  96415. dMotorImpulse2 = this.motorImpulse2 - oldMotorImpulse2;
  96416. }
  96417. if (this.enableMotor3) {
  96418. dMotorImpulse3 = (rvn3 - this.motorSpeed3) * this.dv22;
  96419. this.motorImpulse3 += dMotorImpulse3;
  96420. if (this.motorImpulse3 > this.maxMotorImpulse3) { // clamp motor impulse
  96421. this.motorImpulse3 = this.maxMotorImpulse3;
  96422. } else if (this.motorImpulse3 < -this.maxMotorImpulse3) {
  96423. this.motorImpulse3 = -this.maxMotorImpulse3;
  96424. }
  96425. dMotorImpulse3 = this.motorImpulse3 - oldMotorImpulse3;
  96426. }
  96427. // apply motor impulse to relative velocity
  96428. rvn1 += dMotorImpulse1 * this.kv00 + dMotorImpulse2 * this.k01 + dMotorImpulse3 * this.k02;
  96429. rvn2 += dMotorImpulse1 * this.k10 + dMotorImpulse2 * this.kv11 + dMotorImpulse3 * this.k12;
  96430. rvn3 += dMotorImpulse1 * this.k20 + dMotorImpulse2 * this.k21 + dMotorImpulse3 * this.kv22;
  96431. // subtract target velocity and applied impulse
  96432. rvn1 -= this.limitVelocity1 + this.limitImpulse1 * this.cfm1;
  96433. rvn2 -= this.limitVelocity2 + this.limitImpulse2 * this.cfm2;
  96434. rvn3 -= this.limitVelocity3 + this.limitImpulse3 * this.cfm3;
  96435. var oldLimitImpulse1 = this.limitImpulse1;
  96436. var oldLimitImpulse2 = this.limitImpulse2;
  96437. var oldLimitImpulse3 = this.limitImpulse3;
  96438. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  96439. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  96440. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  96441. this.limitImpulse1 += dLimitImpulse1;
  96442. this.limitImpulse2 += dLimitImpulse2;
  96443. this.limitImpulse3 += dLimitImpulse3;
  96444. // clamp
  96445. var clampState = 0;
  96446. if (this.limitState1 == 2 || this.limitImpulse1 * this.limitState1 < 0) {
  96447. dLimitImpulse1 = -oldLimitImpulse1;
  96448. rvn2 += dLimitImpulse1 * this.k10;
  96449. rvn3 += dLimitImpulse1 * this.k20;
  96450. clampState |= 1;
  96451. }
  96452. if (this.limitState2 == 2 || this.limitImpulse2 * this.limitState2 < 0) {
  96453. dLimitImpulse2 = -oldLimitImpulse2;
  96454. rvn1 += dLimitImpulse2 * this.k01;
  96455. rvn3 += dLimitImpulse2 * this.k21;
  96456. clampState |= 2;
  96457. }
  96458. if (this.limitState3 == 2 || this.limitImpulse3 * this.limitState3 < 0) {
  96459. dLimitImpulse3 = -oldLimitImpulse3;
  96460. rvn1 += dLimitImpulse3 * this.k02;
  96461. rvn2 += dLimitImpulse3 * this.k12;
  96462. clampState |= 4;
  96463. }
  96464. // update un-clamped impulse
  96465. // TODO: isolate division
  96466. var det;
  96467. switch (clampState) {
  96468. case 1:// update 2 3
  96469. det = 1 / (this.k11 * this.k22 - this.k12 * this.k21);
  96470. dLimitImpulse2 = (this.k22 * rvn2 + -this.k12 * rvn3) * det;
  96471. dLimitImpulse3 = (-this.k21 * rvn2 + this.k11 * rvn3) * det;
  96472. break;
  96473. case 2:// update 1 3
  96474. det = 1 / (this.k00 * this.k22 - this.k02 * this.k20);
  96475. dLimitImpulse1 = (this.k22 * rvn1 + -this.k02 * rvn3) * det;
  96476. dLimitImpulse3 = (-this.k20 * rvn1 + this.k00 * rvn3) * det;
  96477. break;
  96478. case 3:// update 3
  96479. dLimitImpulse3 = rvn3 / this.k22;
  96480. break;
  96481. case 4:// update 1 2
  96482. det = 1 / (this.k00 * this.k11 - this.k01 * this.k10);
  96483. dLimitImpulse1 = (this.k11 * rvn1 + -this.k01 * rvn2) * det;
  96484. dLimitImpulse2 = (-this.k10 * rvn1 + this.k00 * rvn2) * det;
  96485. break;
  96486. case 5:// update 2
  96487. dLimitImpulse2 = rvn2 / this.k11;
  96488. break;
  96489. case 6:// update 1
  96490. dLimitImpulse1 = rvn1 / this.k00;
  96491. break;
  96492. }
  96493. this.limitImpulse1 = oldLimitImpulse1 + dLimitImpulse1;
  96494. this.limitImpulse2 = oldLimitImpulse2 + dLimitImpulse2;
  96495. this.limitImpulse3 = oldLimitImpulse3 + dLimitImpulse3;
  96496. var dImpulse1 = dMotorImpulse1 + dLimitImpulse1;
  96497. var dImpulse2 = dMotorImpulse2 + dLimitImpulse2;
  96498. var dImpulse3 = dMotorImpulse3 + dLimitImpulse3;
  96499. // apply impulse
  96500. this.l1.x += dImpulse1 * this.l1x1 + dImpulse2 * this.l1x2 + dImpulse3 * this.l1x3;
  96501. this.l1.y += dImpulse1 * this.l1y1 + dImpulse2 * this.l1y2 + dImpulse3 * this.l1y3;
  96502. this.l1.z += dImpulse1 * this.l1z1 + dImpulse2 * this.l1z2 + dImpulse3 * this.l1z3;
  96503. this.a1.x += dImpulse1 * this.a1x1 + dImpulse2 * this.a1x2 + dImpulse3 * this.a1x3;
  96504. this.a1.y += dImpulse1 * this.a1y1 + dImpulse2 * this.a1y2 + dImpulse3 * this.a1y3;
  96505. this.a1.z += dImpulse1 * this.a1z1 + dImpulse2 * this.a1z2 + dImpulse3 * this.a1z3;
  96506. this.l2.x -= dImpulse1 * this.l2x1 + dImpulse2 * this.l2x2 + dImpulse3 * this.l2x3;
  96507. this.l2.y -= dImpulse1 * this.l2y1 + dImpulse2 * this.l2y2 + dImpulse3 * this.l2y3;
  96508. this.l2.z -= dImpulse1 * this.l2z1 + dImpulse2 * this.l2z2 + dImpulse3 * this.l2z3;
  96509. this.a2.x -= dImpulse1 * this.a2x1 + dImpulse2 * this.a2x2 + dImpulse3 * this.a2x3;
  96510. this.a2.y -= dImpulse1 * this.a2y1 + dImpulse2 * this.a2y2 + dImpulse3 * this.a2y3;
  96511. this.a2.z -= dImpulse1 * this.a2z1 + dImpulse2 * this.a2z2 + dImpulse3 * this.a2z3;
  96512. }
  96513. }
  96514. /**
  96515. * A translational constraint for various joints.
  96516. * @author saharan
  96517. */
  96518. OIMO.TranslationalConstraint = function (joint, limitMotor) {
  96519. this.cfm = NaN;
  96520. this.m1 = NaN;
  96521. this.m2 = NaN;
  96522. this.i1e00 = NaN;
  96523. this.i1e01 = NaN;
  96524. this.i1e02 = NaN;
  96525. this.i1e10 = NaN;
  96526. this.i1e11 = NaN;
  96527. this.i1e12 = NaN;
  96528. this.i1e20 = NaN;
  96529. this.i1e21 = NaN;
  96530. this.i1e22 = NaN;
  96531. this.i2e00 = NaN;
  96532. this.i2e01 = NaN;
  96533. this.i2e02 = NaN;
  96534. this.i2e10 = NaN;
  96535. this.i2e11 = NaN;
  96536. this.i2e12 = NaN;
  96537. this.i2e20 = NaN;
  96538. this.i2e21 = NaN;
  96539. this.i2e22 = NaN;
  96540. this.motorDenom = NaN;
  96541. this.invMotorDenom = NaN;
  96542. this.invDenom = NaN;
  96543. this.ax = NaN;
  96544. this.ay = NaN;
  96545. this.az = NaN;
  96546. this.r1x = NaN;
  96547. this.r1y = NaN;
  96548. this.r1z = NaN;
  96549. this.r2x = NaN;
  96550. this.r2y = NaN;
  96551. this.r2z = NaN;
  96552. this.t1x = NaN;
  96553. this.t1y = NaN;
  96554. this.t1z = NaN;
  96555. this.t2x = NaN;
  96556. this.t2y = NaN;
  96557. this.t2z = NaN;
  96558. this.l1x = NaN;
  96559. this.l1y = NaN;
  96560. this.l1z = NaN;
  96561. this.l2x = NaN;
  96562. this.l2y = NaN;
  96563. this.l2z = NaN;
  96564. this.a1x = NaN;
  96565. this.a1y = NaN;
  96566. this.a1z = NaN;
  96567. this.a2x = NaN;
  96568. this.a2y = NaN;
  96569. this.a2z = NaN;
  96570. this.lowerLimit = NaN;
  96571. this.upperLimit = NaN;
  96572. this.limitVelocity = NaN;
  96573. this.limitState = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  96574. this.enableMotor = false;
  96575. this.motorSpeed = NaN;
  96576. this.maxMotorForce = NaN;
  96577. this.maxMotorImpulse = NaN;
  96578. this.limitMotor = limitMotor;
  96579. this.b1 = joint.body1;
  96580. this.b2 = joint.body2;
  96581. this.p1 = joint.anchorPoint1;
  96582. this.p2 = joint.anchorPoint2;
  96583. this.r1 = joint.relativeAnchorPoint1;
  96584. this.r2 = joint.relativeAnchorPoint2;
  96585. this.l1 = this.b1.linearVelocity;
  96586. this.l2 = this.b2.linearVelocity;
  96587. this.a1 = this.b1.angularVelocity;
  96588. this.a2 = this.b2.angularVelocity;
  96589. this.i1 = this.b1.inverseInertia;
  96590. this.i2 = this.b2.inverseInertia;
  96591. this.limitImpulse = 0;
  96592. this.motorImpulse = 0;
  96593. }
  96594. OIMO.TranslationalConstraint.prototype = {
  96595. constructor: OIMO.TranslationalConstraint,
  96596. preSolve: function (timeStep, invTimeStep) {
  96597. this.ax = this.limitMotor.axis.x;
  96598. this.ay = this.limitMotor.axis.y;
  96599. this.az = this.limitMotor.axis.z;
  96600. this.lowerLimit = this.limitMotor.lowerLimit;
  96601. this.upperLimit = this.limitMotor.upperLimit;
  96602. this.motorSpeed = this.limitMotor.motorSpeed;
  96603. this.maxMotorForce = this.limitMotor.maxMotorForce;
  96604. this.enableMotor = this.maxMotorForce > 0;
  96605. this.m1 = this.b1.inverseMass;
  96606. this.m2 = this.b2.inverseMass;
  96607. var ti1 = this.i1.elements;
  96608. var ti2 = this.i2.elements;
  96609. this.i1e00 = ti1[0];
  96610. this.i1e01 = ti1[1];
  96611. this.i1e02 = ti1[2];
  96612. this.i1e10 = ti1[3];
  96613. this.i1e11 = ti1[4];
  96614. this.i1e12 = ti1[5];
  96615. this.i1e20 = ti1[6];
  96616. this.i1e21 = ti1[7];
  96617. this.i1e22 = ti1[8];
  96618. this.i2e00 = ti2[0];
  96619. this.i2e01 = ti2[1];
  96620. this.i2e02 = ti2[2];
  96621. this.i2e10 = ti2[3];
  96622. this.i2e11 = ti2[4];
  96623. this.i2e12 = ti2[5];
  96624. this.i2e20 = ti2[6];
  96625. this.i2e21 = ti2[7];
  96626. this.i2e22 = ti2[8];
  96627. var dx = this.p2.x - this.p1.x;
  96628. var dy = this.p2.y - this.p1.y;
  96629. var dz = this.p2.z - this.p1.z;
  96630. var d = dx * this.ax + dy * this.ay + dz * this.az;
  96631. var frequency = this.limitMotor.frequency;
  96632. var enableSpring = frequency > 0;
  96633. var enableLimit = this.lowerLimit <= this.upperLimit;
  96634. if (enableSpring && d > 20 || d < -20) {
  96635. enableSpring = false;
  96636. }
  96637. if (enableLimit) {
  96638. if (this.lowerLimit == this.upperLimit) {
  96639. if (this.limitState != 0) {
  96640. this.limitState = 0;
  96641. this.limitImpulse = 0;
  96642. }
  96643. this.limitVelocity = this.lowerLimit - d;
  96644. if (!enableSpring) d = this.lowerLimit;
  96645. } else if (d < this.lowerLimit) {
  96646. if (this.limitState != -1) {
  96647. this.limitState = -1;
  96648. this.limitImpulse = 0;
  96649. }
  96650. this.limitVelocity = this.lowerLimit - d;
  96651. if (!enableSpring) d = this.lowerLimit;
  96652. } else if (d > this.upperLimit) {
  96653. if (this.limitState != 1) {
  96654. this.limitState = 1;
  96655. this.limitImpulse = 0;
  96656. }
  96657. this.limitVelocity = this.upperLimit - d;
  96658. if (!enableSpring) d = this.upperLimit;
  96659. } else {
  96660. this.limitState = 2;
  96661. this.limitImpulse = 0;
  96662. this.limitVelocity = 0;
  96663. }
  96664. if (!enableSpring) {
  96665. if (this.limitVelocity > 0.005) this.limitVelocity -= 0.005;
  96666. else if (this.limitVelocity < -0.005) this.limitVelocity += 0.005;
  96667. else this.limitVelocity = 0;
  96668. }
  96669. } else {
  96670. this.limitState = 2;
  96671. this.limitImpulse = 0;
  96672. }
  96673. if (this.enableMotor && (this.limitState != 0 || enableSpring)) {
  96674. this.maxMotorImpulse = this.maxMotorForce * timeStep;
  96675. } else {
  96676. this.motorImpulse = 0;
  96677. this.maxMotorImpulse = 0;
  96678. }
  96679. var rdx = d * this.ax;
  96680. var rdy = d * this.ay;
  96681. var rdz = d * this.az;
  96682. var w1 = this.m1 / (this.m1 + this.m2);
  96683. var w2 = 1 - w1;
  96684. this.r1x = this.r1.x + rdx * w1;
  96685. this.r1y = this.r1.y + rdy * w1;
  96686. this.r1z = this.r1.z + rdz * w1;
  96687. this.r2x = this.r2.x - rdx * w2;
  96688. this.r2y = this.r2.y - rdy * w2;
  96689. this.r2z = this.r2.z - rdz * w2;
  96690. this.t1x = this.r1y * this.az - this.r1z * this.ay;
  96691. this.t1y = this.r1z * this.ax - this.r1x * this.az;
  96692. this.t1z = this.r1x * this.ay - this.r1y * this.ax;
  96693. this.t2x = this.r2y * this.az - this.r2z * this.ay;
  96694. this.t2y = this.r2z * this.ax - this.r2x * this.az;
  96695. this.t2z = this.r2x * this.ay - this.r2y * this.ax;
  96696. this.l1x = this.ax * this.m1;
  96697. this.l1y = this.ay * this.m1;
  96698. this.l1z = this.az * this.m1;
  96699. this.l2x = this.ax * this.m2;
  96700. this.l2y = this.ay * this.m2;
  96701. this.l2z = this.az * this.m2;
  96702. this.a1x = this.t1x * this.i1e00 + this.t1y * this.i1e01 + this.t1z * this.i1e02;
  96703. this.a1y = this.t1x * this.i1e10 + this.t1y * this.i1e11 + this.t1z * this.i1e12;
  96704. this.a1z = this.t1x * this.i1e20 + this.t1y * this.i1e21 + this.t1z * this.i1e22;
  96705. this.a2x = this.t2x * this.i2e00 + this.t2y * this.i2e01 + this.t2z * this.i2e02;
  96706. this.a2y = this.t2x * this.i2e10 + this.t2y * this.i2e11 + this.t2z * this.i2e12;
  96707. this.a2z = this.t2x * this.i2e20 + this.t2y * this.i2e21 + this.t2z * this.i2e22;
  96708. this.motorDenom =
  96709. this.m1 + this.m2 +
  96710. this.ax * (this.a1y * this.r1z - this.a1z * this.r1y + this.a2y * this.r2z - this.a2z * this.r2y) +
  96711. this.ay * (this.a1z * this.r1x - this.a1x * this.r1z + this.a2z * this.r2x - this.a2x * this.r2z) +
  96712. this.az * (this.a1x * this.r1y - this.a1y * this.r1x + this.a2x * this.r2y - this.a2y * this.r2x);
  96713. this.invMotorDenom = 1 / this.motorDenom;
  96714. if (enableSpring && this.limitState != 2) {
  96715. var omega = 6.2831853 * frequency;
  96716. var k = omega * omega * timeStep;
  96717. var dmp = invTimeStep / (k + 2 * this.limitMotor.dampingRatio * omega);
  96718. this.cfm = this.motorDenom * dmp;
  96719. this.limitVelocity *= k * dmp;
  96720. } else {
  96721. this.cfm = 0;
  96722. this.limitVelocity *= invTimeStep * 0.05;
  96723. }
  96724. this.invDenom = 1 / (this.motorDenom + this.cfm);
  96725. var totalImpulse = this.limitImpulse + this.motorImpulse;
  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. solve: function () {
  96740. var rvn =
  96741. this.ax * (this.l2.x - this.l1.x) + this.ay * (this.l2.y - this.l1.y) + this.az * (this.l2.z - this.l1.z) +
  96742. 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;
  96743. // motor part
  96744. var newMotorImpulse;
  96745. if (this.enableMotor) {
  96746. newMotorImpulse = (rvn - this.motorSpeed) * this.invMotorDenom;
  96747. var oldMotorImpulse = this.motorImpulse;
  96748. this.motorImpulse += newMotorImpulse;
  96749. if (this.motorImpulse > this.maxMotorImpulse) this.motorImpulse = this.maxMotorImpulse;
  96750. else if (this.motorImpulse < -this.maxMotorImpulse) this.motorImpulse = -this.maxMotorImpulse;
  96751. newMotorImpulse = this.motorImpulse - oldMotorImpulse;
  96752. rvn -= newMotorImpulse * this.motorDenom;
  96753. } else newMotorImpulse = 0;
  96754. // limit part
  96755. var newLimitImpulse;
  96756. if (this.limitState != 2) {
  96757. newLimitImpulse = (rvn - this.limitVelocity - this.limitImpulse * this.cfm) * this.invDenom;
  96758. var oldLimitImpulse = this.limitImpulse;
  96759. this.limitImpulse += newLimitImpulse;
  96760. if (this.limitImpulse * this.limitState < 0) this.limitImpulse = 0;
  96761. newLimitImpulse = this.limitImpulse - oldLimitImpulse;
  96762. } else newLimitImpulse = 0;
  96763. var totalImpulse = newLimitImpulse + newMotorImpulse;
  96764. this.l1.x += totalImpulse * this.l1x;
  96765. this.l1.y += totalImpulse * this.l1y;
  96766. this.l1.z += totalImpulse * this.l1z;
  96767. this.a1.x += totalImpulse * this.a1x;
  96768. this.a1.y += totalImpulse * this.a1y;
  96769. this.a1.z += totalImpulse * this.a1z;
  96770. this.l2.x -= totalImpulse * this.l2x;
  96771. this.l2.y -= totalImpulse * this.l2y;
  96772. this.l2.z -= totalImpulse * this.l2z;
  96773. this.a2.x -= totalImpulse * this.a2x;
  96774. this.a2.y -= totalImpulse * this.a2y;
  96775. this.a2.z -= totalImpulse * this.a2z;
  96776. }
  96777. }
  96778. /**
  96779. * A contact is a pair of shapes whose axis-aligned bounding boxes are overlapping.
  96780. * @author saharan
  96781. */
  96782. OIMO.Contact = function () {
  96783. // The first shape.
  96784. this.shape1 = null;
  96785. // The second shape.
  96786. this.shape2 = null;
  96787. // The first rigid body.
  96788. this.body1 = null;
  96789. // The second rigid body.
  96790. this.body2 = null;
  96791. // The previous contact in the world.
  96792. this.prev = null;
  96793. // The next contact in the world.
  96794. this.next = null;
  96795. // Internal
  96796. this.persisting = false;
  96797. // Whether both the rigid bodies are sleeping or not.
  96798. this.sleeping = false;
  96799. // The collision detector between two shapes.
  96800. this.detector = null;
  96801. // The contact constraint of the contact.
  96802. this.constraint = null;
  96803. // Whether the shapes are touching or not.
  96804. this.touching = false;
  96805. this.b1Link = new OIMO.ContactLink(this);
  96806. this.b2Link = new OIMO.ContactLink(this);
  96807. this.s1Link = new OIMO.ContactLink(this);
  96808. this.s2Link = new OIMO.ContactLink(this);
  96809. // The contact manifold of the contact.
  96810. this.manifold = new OIMO.ContactManifold();
  96811. this.buffer = [];// vector 4
  96812. this.buffer.length = 4;
  96813. this.buffer[0] = new OIMO.ImpulseDataBuffer();
  96814. this.buffer[1] = new OIMO.ImpulseDataBuffer();
  96815. this.buffer[2] = new OIMO.ImpulseDataBuffer();
  96816. this.buffer[3] = new OIMO.ImpulseDataBuffer();
  96817. this.points = this.manifold.points;
  96818. this.constraint = new OIMO.ContactConstraint(this.manifold);
  96819. }
  96820. OIMO.Contact.prototype = {
  96821. constructor: OIMO.Contact,
  96822. mixRestitution: function (restitution1, restitution2) {
  96823. return OIMO.sqrt(restitution1 * restitution2);
  96824. },
  96825. mixFriction: function (friction1, friction2) {
  96826. return OIMO.sqrt(friction1 * friction2);
  96827. },
  96828. /**
  96829. * Update the contact manifold.
  96830. */
  96831. updateManifold: function () {
  96832. this.constraint.restitution = this.mixRestitution(this.shape1.restitution, this.shape2.restitution);
  96833. this.constraint.friction = this.mixFriction(this.shape1.friction, this.shape2.friction);
  96834. var numBuffers = this.manifold.numPoints;
  96835. var i = numBuffers;
  96836. while (i--) {
  96837. //for(var i=0;i<numBuffers;i++){
  96838. var b = this.buffer[i];
  96839. var p = this.points[i];
  96840. b.lp1X = p.localPoint1.x;
  96841. b.lp1Y = p.localPoint1.y;
  96842. b.lp1Z = p.localPoint1.z;
  96843. b.lp2X = p.localPoint2.x;
  96844. b.lp2Y = p.localPoint2.y;
  96845. b.lp2Z = p.localPoint2.z;
  96846. b.impulse = p.normalImpulse;
  96847. }
  96848. this.manifold.numPoints = 0;
  96849. this.detector.detectCollision(this.shape1, this.shape2, this.manifold);
  96850. var num = this.manifold.numPoints;
  96851. if (num == 0) {
  96852. this.touching = false;
  96853. return;
  96854. }
  96855. this.touching = true;
  96856. i = num;
  96857. while (i--) {
  96858. //for(i=0; i<num; i++){
  96859. p = this.points[i];
  96860. var lp1x = p.localPoint1.x;
  96861. var lp1y = p.localPoint1.y;
  96862. var lp1z = p.localPoint1.z;
  96863. var lp2x = p.localPoint2.x;
  96864. var lp2y = p.localPoint2.y;
  96865. var lp2z = p.localPoint2.z;
  96866. var index = -1;
  96867. var minDistance = 0.0004;
  96868. var j = numBuffers;
  96869. while (j--) {
  96870. //for(var j=0;j<numBuffers;j++){
  96871. b = this.buffer[j];
  96872. var dx = b.lp1X - lp1x;
  96873. var dy = b.lp1Y - lp1y;
  96874. var dz = b.lp1Z - lp1z;
  96875. var distance1 = dx * dx + dy * dy + dz * dz;
  96876. dx = b.lp2X - lp2x;
  96877. dy = b.lp2Y - lp2y;
  96878. dz = b.lp2Z - lp2z;
  96879. var distance2 = dx * dx + dy * dy + dz * dz;
  96880. if (distance1 < distance2) {
  96881. if (distance1 < minDistance) {
  96882. minDistance = distance1;
  96883. index = j;
  96884. }
  96885. } else {
  96886. if (distance2 < minDistance) {
  96887. minDistance = distance2;
  96888. index = j;
  96889. }
  96890. }
  96891. }
  96892. if (index != -1) {
  96893. var tmp = this.buffer[index];
  96894. this.buffer[index] = this.buffer[--numBuffers];
  96895. this.buffer[numBuffers] = tmp;
  96896. p.normalImpulse = tmp.impulse;
  96897. p.warmStarted = true;
  96898. } else {
  96899. p.normalImpulse = 0;
  96900. p.warmStarted = false;
  96901. }
  96902. }
  96903. },
  96904. /**
  96905. * Attach the contact to the shapes.
  96906. * @param shape1
  96907. * @param shape2
  96908. */
  96909. attach: function (shape1, shape2) {
  96910. this.shape1 = shape1;
  96911. this.shape2 = shape2;
  96912. this.body1 = shape1.parent;
  96913. this.body2 = shape2.parent;
  96914. this.manifold.body1 = this.body1;
  96915. this.manifold.body2 = this.body2;
  96916. this.constraint.body1 = this.body1;
  96917. this.constraint.body2 = this.body2;
  96918. this.constraint.attach();
  96919. this.s1Link.shape = shape2;
  96920. this.s1Link.body = this.body2;
  96921. this.s2Link.shape = shape1;
  96922. this.s2Link.body = this.body1;
  96923. if (shape1.contactLink != null) (this.s1Link.next = shape1.contactLink).prev = this.s1Link;
  96924. else this.s1Link.next = null;
  96925. shape1.contactLink = this.s1Link;
  96926. shape1.numContacts++;
  96927. if (shape2.contactLink != null) (this.s2Link.next = shape2.contactLink).prev = this.s2Link;
  96928. else this.s2Link.next = null;
  96929. shape2.contactLink = this.s2Link;
  96930. shape2.numContacts++;
  96931. this.b1Link.shape = shape2;
  96932. this.b1Link.body = this.body2;
  96933. this.b2Link.shape = shape1;
  96934. this.b2Link.body = this.body1;
  96935. if (this.body1.contactLink != null) (this.b1Link.next = this.body1.contactLink).prev = this.b1Link;
  96936. else this.b1Link.next = null;
  96937. this.body1.contactLink = this.b1Link;
  96938. this.body1.numContacts++;
  96939. if (this.body2.contactLink != null) (this.b2Link.next = this.body2.contactLink).prev = this.b2Link;
  96940. else this.b2Link.next = null;
  96941. this.body2.contactLink = this.b2Link;
  96942. this.body2.numContacts++;
  96943. this.prev = null;
  96944. this.next = null;
  96945. this.persisting = true;
  96946. this.sleeping = this.body1.sleeping && this.body2.sleeping;
  96947. this.manifold.numPoints = 0;
  96948. },
  96949. /**
  96950. * Detach the contact from the shapes.
  96951. */
  96952. detach: function () {
  96953. var prev = this.s1Link.prev;
  96954. var next = this.s1Link.next;
  96955. if (prev !== null) prev.next = next;
  96956. if (next !== null) next.prev = prev;
  96957. if (this.shape1.contactLink == this.s1Link) this.shape1.contactLink = next;
  96958. this.s1Link.prev = null;
  96959. this.s1Link.next = null;
  96960. this.s1Link.shape = null;
  96961. this.s1Link.body = null;
  96962. this.shape1.numContacts--;
  96963. prev = this.s2Link.prev;
  96964. next = this.s2Link.next;
  96965. if (prev !== null) prev.next = next;
  96966. if (next !== null) next.prev = prev;
  96967. if (this.shape2.contactLink == this.s2Link) this.shape2.contactLink = next;
  96968. this.s2Link.prev = null;
  96969. this.s2Link.next = null;
  96970. this.s2Link.shape = null;
  96971. this.s2Link.body = null;
  96972. this.shape2.numContacts--;
  96973. prev = this.b1Link.prev;
  96974. next = this.b1Link.next;
  96975. if (prev !== null) prev.next = next;
  96976. if (next !== null) next.prev = prev;
  96977. if (this.body1.contactLink == this.b1Link) this.body1.contactLink = next;
  96978. this.b1Link.prev = null;
  96979. this.b1Link.next = null;
  96980. this.b1Link.shape = null;
  96981. this.b1Link.body = null;
  96982. this.body1.numContacts--;
  96983. prev = this.b2Link.prev;
  96984. next = this.b2Link.next;
  96985. if (prev !== null) prev.next = next;
  96986. if (next !== null) next.prev = prev;
  96987. if (this.body2.contactLink == this.b2Link) this.body2.contactLink = next;
  96988. this.b2Link.prev = null;
  96989. this.b2Link.next = null;
  96990. this.b2Link.shape = null;
  96991. this.b2Link.body = null;
  96992. this.body2.numContacts--;
  96993. this.manifold.body1 = null;
  96994. this.manifold.body2 = null;
  96995. this.constraint.body1 = null;
  96996. this.constraint.body2 = null;
  96997. this.constraint.detach();
  96998. this.shape1 = null;
  96999. this.shape2 = null;
  97000. this.body1 = null;
  97001. this.body2 = null;
  97002. }
  97003. }
  97004. /**
  97005. * ...
  97006. * @author saharan
  97007. */
  97008. OIMO.ContactConstraint = function (manifold) {
  97009. OIMO.Constraint.call(this);
  97010. // The contact manifold of the constraint.
  97011. this.manifold = manifold;
  97012. // The coefficient of restitution of the constraint.
  97013. this.restitution = NaN;
  97014. // The coefficient of friction of the constraint.
  97015. this.friction = NaN;
  97016. this.p1 = null;
  97017. this.p2 = null;
  97018. this.lv1 = null;
  97019. this.lv2 = null;
  97020. this.av1 = null;
  97021. this.av2 = null;
  97022. this.i1 = null;
  97023. this.i2 = null;
  97024. this.ii1 = null;
  97025. this.ii2 = null;
  97026. this.m1 = NaN;
  97027. this.m2 = NaN;
  97028. this.num = 0;
  97029. this.ps = manifold.points;
  97030. this.cs = new OIMO.ContactPointDataBuffer();
  97031. this.cs.next = new OIMO.ContactPointDataBuffer();
  97032. this.cs.next.next = new OIMO.ContactPointDataBuffer();
  97033. this.cs.next.next.next = new OIMO.ContactPointDataBuffer();
  97034. }
  97035. OIMO.ContactConstraint.prototype = Object.create(OIMO.Constraint.prototype);
  97036. /**
  97037. * Attach the constraint to the bodies.
  97038. */
  97039. OIMO.ContactConstraint.prototype.attach = function () {
  97040. this.p1 = this.body1.position;
  97041. this.p2 = this.body2.position;
  97042. this.lv1 = this.body1.linearVelocity;
  97043. this.av1 = this.body1.angularVelocity;
  97044. this.lv2 = this.body2.linearVelocity;
  97045. this.av2 = this.body2.angularVelocity;
  97046. this.i1 = this.body1.inverseInertia;
  97047. this.i2 = this.body2.inverseInertia;
  97048. }
  97049. /**
  97050. * Detach the constraint from the bodies.
  97051. */
  97052. OIMO.ContactConstraint.prototype.detach = function () {
  97053. this.p1 = null;
  97054. this.p2 = null;
  97055. this.lv1 = null;
  97056. this.lv2 = null;
  97057. this.av1 = null;
  97058. this.av2 = null;
  97059. this.i1 = null;
  97060. this.i2 = null;
  97061. }
  97062. OIMO.ContactConstraint.prototype.preSolve = function (timeStep, invTimeStep) {
  97063. this.m1 = this.body1.inverseMass;
  97064. this.m2 = this.body2.inverseMass;
  97065. this.ii1 = this.i1.clone();
  97066. this.ii2 = this.i2.clone();
  97067. var ii1 = this.ii1.elements;
  97068. var ii2 = this.ii2.elements;
  97069. var p1x = this.p1.x;
  97070. var p1y = this.p1.y;
  97071. var p1z = this.p1.z;
  97072. var p2x = this.p2.x;
  97073. var p2y = this.p2.y;
  97074. var p2z = this.p2.z;
  97075. var m1m2 = this.m1 + this.m2;
  97076. this.num = this.manifold.numPoints;
  97077. var c = this.cs;
  97078. for (var i = 0; i < this.num; i++) {
  97079. var p = this.ps[i];
  97080. var tmp1X;
  97081. var tmp1Y;
  97082. var tmp1Z;
  97083. var tmp2X;
  97084. var tmp2Y;
  97085. var tmp2Z;
  97086. tmp1X = p.position.x;
  97087. tmp1Y = p.position.y;
  97088. tmp1Z = p.position.z;
  97089. var rp1X = tmp1X - p1x;
  97090. var rp1Y = tmp1Y - p1y;
  97091. var rp1Z = tmp1Z - p1z;
  97092. var rp2X = tmp1X - p2x;
  97093. var rp2Y = tmp1Y - p2y;
  97094. var rp2Z = tmp1Z - p2z;
  97095. c.rp1X = rp1X;
  97096. c.rp1Y = rp1Y;
  97097. c.rp1Z = rp1Z;
  97098. c.rp2X = rp2X;
  97099. c.rp2Y = rp2Y;
  97100. c.rp2Z = rp2Z;
  97101. c.norImp = p.normalImpulse;
  97102. c.tanImp = p.tangentImpulse;
  97103. c.binImp = p.binormalImpulse;
  97104. var norX = p.normal.x;
  97105. var norY = p.normal.y;
  97106. var norZ = p.normal.z;
  97107. var rvX = (this.lv2.x + this.av2.y * rp2Z - this.av2.z * rp2Y) - (this.lv1.x + this.av1.y * rp1Z - this.av1.z * rp1Y);
  97108. var rvY = (this.lv2.y + this.av2.z * rp2X - this.av2.x * rp2Z) - (this.lv1.y + this.av1.z * rp1X - this.av1.x * rp1Z);
  97109. var rvZ = (this.lv2.z + this.av2.x * rp2Y - this.av2.y * rp2X) - (this.lv1.z + this.av1.x * rp1Y - this.av1.y * rp1X);
  97110. var rvn = norX * rvX + norY * rvY + norZ * rvZ;
  97111. var tanX = rvX - rvn * norX;
  97112. var tanY = rvY - rvn * norY;
  97113. var tanZ = rvZ - rvn * norZ;
  97114. var len = tanX * tanX + tanY * tanY + tanZ * tanZ;
  97115. if (len > 0.04) {
  97116. len = 1 / OIMO.sqrt(len);
  97117. } else {
  97118. tanX = norY * norX - norZ * norZ;
  97119. tanY = -norZ * norY - norX * norX;
  97120. tanZ = norX * norZ + norY * norY;
  97121. len = 1 / OIMO.sqrt(tanX * tanX + tanY * tanY + tanZ * tanZ);
  97122. }
  97123. tanX *= len;
  97124. tanY *= len;
  97125. tanZ *= len;
  97126. var binX = norY * tanZ - norZ * tanY;
  97127. var binY = norZ * tanX - norX * tanZ;
  97128. var binZ = norX * tanY - norY * tanX;
  97129. c.norX = norX;
  97130. c.norY = norY;
  97131. c.norZ = norZ;
  97132. c.tanX = tanX;
  97133. c.tanY = tanY;
  97134. c.tanZ = tanZ;
  97135. c.binX = binX;
  97136. c.binY = binY;
  97137. c.binZ = binZ;
  97138. c.norU1X = norX * this.m1;
  97139. c.norU1Y = norY * this.m1;
  97140. c.norU1Z = norZ * this.m1;
  97141. c.norU2X = norX * this.m2;
  97142. c.norU2Y = norY * this.m2;
  97143. c.norU2Z = norZ * this.m2;
  97144. c.tanU1X = tanX * this.m1;
  97145. c.tanU1Y = tanY * this.m1;
  97146. c.tanU1Z = tanZ * this.m1;
  97147. c.tanU2X = tanX * this.m2;
  97148. c.tanU2Y = tanY * this.m2;
  97149. c.tanU2Z = tanZ * this.m2;
  97150. c.binU1X = binX * this.m1;
  97151. c.binU1Y = binY * this.m1;
  97152. c.binU1Z = binZ * this.m1;
  97153. c.binU2X = binX * this.m2;
  97154. c.binU2Y = binY * this.m2;
  97155. c.binU2Z = binZ * this.m2;
  97156. var norT1X = rp1Y * norZ - rp1Z * norY;
  97157. var norT1Y = rp1Z * norX - rp1X * norZ;
  97158. var norT1Z = rp1X * norY - rp1Y * norX;
  97159. var norT2X = rp2Y * norZ - rp2Z * norY;
  97160. var norT2Y = rp2Z * norX - rp2X * norZ;
  97161. var norT2Z = rp2X * norY - rp2Y * norX;
  97162. var tanT1X = rp1Y * tanZ - rp1Z * tanY;
  97163. var tanT1Y = rp1Z * tanX - rp1X * tanZ;
  97164. var tanT1Z = rp1X * tanY - rp1Y * tanX;
  97165. var tanT2X = rp2Y * tanZ - rp2Z * tanY;
  97166. var tanT2Y = rp2Z * tanX - rp2X * tanZ;
  97167. var tanT2Z = rp2X * tanY - rp2Y * tanX;
  97168. var binT1X = rp1Y * binZ - rp1Z * binY;
  97169. var binT1Y = rp1Z * binX - rp1X * binZ;
  97170. var binT1Z = rp1X * binY - rp1Y * binX;
  97171. var binT2X = rp2Y * binZ - rp2Z * binY;
  97172. var binT2Y = rp2Z * binX - rp2X * binZ;
  97173. var binT2Z = rp2X * binY - rp2Y * binX;
  97174. var norTU1X = norT1X * ii1[0] + norT1Y * ii1[1] + norT1Z * ii1[2];
  97175. var norTU1Y = norT1X * ii1[3] + norT1Y * ii1[4] + norT1Z * ii1[5];
  97176. var norTU1Z = norT1X * ii1[6] + norT1Y * ii1[7] + norT1Z * ii1[8];
  97177. var norTU2X = norT2X * ii2[0] + norT2Y * ii2[1] + norT2Z * ii2[2];
  97178. var norTU2Y = norT2X * ii2[3] + norT2Y * ii2[4] + norT2Z * ii2[5];
  97179. var norTU2Z = norT2X * ii2[6] + norT2Y * ii2[7] + norT2Z * ii2[8];
  97180. var tanTU1X = tanT1X * ii1[0] + tanT1Y * ii1[1] + tanT1Z * ii1[2];
  97181. var tanTU1Y = tanT1X * ii1[3] + tanT1Y * ii1[4] + tanT1Z * ii1[5];
  97182. var tanTU1Z = tanT1X * ii1[6] + tanT1Y * ii1[7] + tanT1Z * ii1[8];
  97183. var tanTU2X = tanT2X * ii2[0] + tanT2Y * ii2[1] + tanT2Z * ii2[2];
  97184. var tanTU2Y = tanT2X * ii2[3] + tanT2Y * ii2[4] + tanT2Z * ii2[5];
  97185. var tanTU2Z = tanT2X * ii2[6] + tanT2Y * ii2[7] + tanT2Z * ii2[8];
  97186. var binTU1X = binT1X * ii1[0] + binT1Y * ii1[1] + binT1Z * ii1[2];
  97187. var binTU1Y = binT1X * ii1[3] + binT1Y * ii1[4] + binT1Z * ii1[5];
  97188. var binTU1Z = binT1X * ii1[6] + binT1Y * ii1[7] + binT1Z * ii1[8];
  97189. var binTU2X = binT2X * ii2[0] + binT2Y * ii2[1] + binT2Z * ii2[2];
  97190. var binTU2Y = binT2X * ii2[3] + binT2Y * ii2[4] + binT2Z * ii2[5];
  97191. var binTU2Z = binT2X * ii2[6] + binT2Y * ii2[7] + binT2Z * ii2[8];
  97192. c.norT1X = norT1X;
  97193. c.norT1Y = norT1Y;
  97194. c.norT1Z = norT1Z;
  97195. c.tanT1X = tanT1X;
  97196. c.tanT1Y = tanT1Y;
  97197. c.tanT1Z = tanT1Z;
  97198. c.binT1X = binT1X;
  97199. c.binT1Y = binT1Y;
  97200. c.binT1Z = binT1Z;
  97201. c.norT2X = norT2X;
  97202. c.norT2Y = norT2Y;
  97203. c.norT2Z = norT2Z;
  97204. c.tanT2X = tanT2X;
  97205. c.tanT2Y = tanT2Y;
  97206. c.tanT2Z = tanT2Z;
  97207. c.binT2X = binT2X;
  97208. c.binT2Y = binT2Y;
  97209. c.binT2Z = binT2Z;
  97210. c.norTU1X = norTU1X;
  97211. c.norTU1Y = norTU1Y;
  97212. c.norTU1Z = norTU1Z;
  97213. c.tanTU1X = tanTU1X;
  97214. c.tanTU1Y = tanTU1Y;
  97215. c.tanTU1Z = tanTU1Z;
  97216. c.binTU1X = binTU1X;
  97217. c.binTU1Y = binTU1Y;
  97218. c.binTU1Z = binTU1Z;
  97219. c.norTU2X = norTU2X;
  97220. c.norTU2Y = norTU2Y;
  97221. c.norTU2Z = norTU2Z;
  97222. c.tanTU2X = tanTU2X;
  97223. c.tanTU2Y = tanTU2Y;
  97224. c.tanTU2Z = tanTU2Z;
  97225. c.binTU2X = binTU2X;
  97226. c.binTU2Y = binTU2Y;
  97227. c.binTU2Z = binTU2Z;
  97228. tmp1X = norT1X * ii1[0] + norT1Y * ii1[1] + norT1Z * ii1[2];
  97229. tmp1Y = norT1X * ii1[3] + norT1Y * ii1[4] + norT1Z * ii1[5];
  97230. tmp1Z = norT1X * ii1[6] + norT1Y * ii1[7] + norT1Z * ii1[8];
  97231. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  97232. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  97233. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  97234. tmp1X = norT2X * ii2[0] + norT2Y * ii2[1] + norT2Z * ii2[2];
  97235. tmp1Y = norT2X * ii2[3] + norT2Y * ii2[4] + norT2Z * ii2[5];
  97236. tmp1Z = norT2X * ii2[6] + norT2Y * ii2[7] + norT2Z * ii2[8];
  97237. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  97238. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  97239. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  97240. var norDen = 1 / (m1m2 + norX * tmp2X + norY * tmp2Y + norZ * tmp2Z);
  97241. tmp1X = tanT1X * ii1[0] + tanT1Y * ii1[1] + tanT1Z * ii1[2];
  97242. tmp1Y = tanT1X * ii1[3] + tanT1Y * ii1[4] + tanT1Z * ii1[5];
  97243. tmp1Z = tanT1X * ii1[6] + tanT1Y * ii1[7] + tanT1Z * ii1[8];
  97244. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  97245. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  97246. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  97247. tmp1X = tanT2X * ii2[0] + tanT2Y * ii2[1] + tanT2Z * ii2[2];
  97248. tmp1Y = tanT2X * ii2[3] + tanT2Y * ii2[4] + tanT2Z * ii2[5];
  97249. tmp1Z = tanT2X * ii2[6] + tanT2Y * ii2[7] + tanT2Z * ii2[8];
  97250. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  97251. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  97252. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  97253. var tanDen = 1 / (m1m2 + tanX * tmp2X + tanY * tmp2Y + tanZ * tmp2Z);
  97254. tmp1X = binT1X * ii1[0] + binT1Y * ii1[1] + binT1Z * ii1[2];
  97255. tmp1Y = binT1X * ii1[3] + binT1Y * ii1[4] + binT1Z * ii1[5];
  97256. tmp1Z = binT1X * ii1[6] + binT1Y * ii1[7] + binT1Z * ii1[8];
  97257. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  97258. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  97259. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  97260. tmp1X = binT2X * ii2[0] + binT2Y * ii2[1] + binT2Z * ii2[2];
  97261. tmp1Y = binT2X * ii2[3] + binT2Y * ii2[4] + binT2Z * ii2[5];
  97262. tmp1Z = binT2X * ii2[6] + binT2Y * ii2[7] + binT2Z * ii2[8];
  97263. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  97264. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  97265. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  97266. var binDen = 1 / (m1m2 + binX * tmp2X + binY * tmp2Y + binZ * tmp2Z);
  97267. c.norDen = norDen;
  97268. c.tanDen = tanDen;
  97269. c.binDen = binDen;
  97270. if (p.warmStarted) {
  97271. var norImp = p.normalImpulse;
  97272. this.lv1.x += c.norU1X * norImp;
  97273. this.lv1.y += c.norU1Y * norImp;
  97274. this.lv1.z += c.norU1Z * norImp;
  97275. this.av1.x += norTU1X * norImp;
  97276. this.av1.y += norTU1Y * norImp;
  97277. this.av1.z += norTU1Z * norImp;
  97278. this.lv2.x -= c.norU2X * norImp;
  97279. this.lv2.y -= c.norU2Y * norImp;
  97280. this.lv2.z -= c.norU2Z * norImp;
  97281. this.av2.x -= norTU2X * norImp;
  97282. this.av2.y -= norTU2Y * norImp;
  97283. this.av2.z -= norTU2Z * norImp;
  97284. c.norImp = norImp;
  97285. c.tanImp = 0;
  97286. c.binImp = 0;
  97287. rvn = 0; // disable bouncing
  97288. } else {
  97289. c.norImp = 0;
  97290. c.tanImp = 0;
  97291. c.binImp = 0;
  97292. }
  97293. if (rvn > -1) {
  97294. rvn = 0; // disable bouncing
  97295. }
  97296. var norTar = this.restitution * -rvn;
  97297. var sepV = -(p.penetration + 0.005) * invTimeStep * 0.05; // allow 0.5cm error
  97298. if (norTar < sepV) norTar = sepV;
  97299. c.norTar = norTar;
  97300. c.last = i == this.num - 1;
  97301. c = c.next;
  97302. }
  97303. }
  97304. OIMO.ContactConstraint.prototype.solve = function () {
  97305. var lv1x = this.lv1.x;
  97306. var lv1y = this.lv1.y;
  97307. var lv1z = this.lv1.z;
  97308. var lv2x = this.lv2.x;
  97309. var lv2y = this.lv2.y;
  97310. var lv2z = this.lv2.z;
  97311. var av1x = this.av1.x;
  97312. var av1y = this.av1.y;
  97313. var av1z = this.av1.z;
  97314. var av2x = this.av2.x;
  97315. var av2y = this.av2.y;
  97316. var av2z = this.av2.z;
  97317. var c = this.cs;
  97318. while (true) {
  97319. var oldImp1;
  97320. var newImp1;
  97321. var oldImp2;
  97322. var newImp2;
  97323. var rvn;
  97324. var norImp = c.norImp;
  97325. var tanImp = c.tanImp;
  97326. var binImp = c.binImp;
  97327. var max = -norImp * this.friction;
  97328. var rvX = lv2x - lv1x;
  97329. var rvY = lv2y - lv1y;
  97330. var rvZ = lv2z - lv1z;
  97331. rvn =
  97332. rvX * c.tanX + rvY * c.tanY + rvZ * c.tanZ +
  97333. av2x * c.tanT2X + av2y * c.tanT2Y + av2z * c.tanT2Z -
  97334. av1x * c.tanT1X - av1y * c.tanT1Y - av1z * c.tanT1Z
  97335. ;
  97336. oldImp1 = tanImp;
  97337. newImp1 = rvn * c.tanDen;
  97338. tanImp += newImp1;
  97339. rvn =
  97340. rvX * c.binX + rvY * c.binY + rvZ * c.binZ +
  97341. av2x * c.binT2X + av2y * c.binT2Y + av2z * c.binT2Z -
  97342. av1x * c.binT1X - av1y * c.binT1Y - av1z * c.binT1Z
  97343. ;
  97344. oldImp2 = binImp;
  97345. newImp2 = rvn * c.binDen;
  97346. binImp += newImp2;
  97347. // cone friction clamp
  97348. var len = tanImp * tanImp + binImp * binImp;
  97349. if (len > max * max) {
  97350. len = max / OIMO.sqrt(len);
  97351. tanImp *= len;
  97352. binImp *= len;
  97353. }
  97354. newImp1 = tanImp - oldImp1;
  97355. newImp2 = binImp - oldImp2;
  97356. lv1x += c.tanU1X * newImp1 + c.binU1X * newImp2;
  97357. lv1y += c.tanU1Y * newImp1 + c.binU1Y * newImp2;
  97358. lv1z += c.tanU1Z * newImp1 + c.binU1Z * newImp2;
  97359. av1x += c.tanTU1X * newImp1 + c.binTU1X * newImp2;
  97360. av1y += c.tanTU1Y * newImp1 + c.binTU1Y * newImp2;
  97361. av1z += c.tanTU1Z * newImp1 + c.binTU1Z * newImp2;
  97362. lv2x -= c.tanU2X * newImp1 + c.binU2X * newImp2;
  97363. lv2y -= c.tanU2Y * newImp1 + c.binU2Y * newImp2;
  97364. lv2z -= c.tanU2Z * newImp1 + c.binU2Z * newImp2;
  97365. av2x -= c.tanTU2X * newImp1 + c.binTU2X * newImp2;
  97366. av2y -= c.tanTU2Y * newImp1 + c.binTU2Y * newImp2;
  97367. av2z -= c.tanTU2Z * newImp1 + c.binTU2Z * newImp2;
  97368. // restitution part
  97369. rvn =
  97370. (lv2x - lv1x) * c.norX + (lv2y - lv1y) * c.norY + (lv2z - lv1z) * c.norZ +
  97371. av2x * c.norT2X + av2y * c.norT2Y + av2z * c.norT2Z -
  97372. av1x * c.norT1X - av1y * c.norT1Y - av1z * c.norT1Z;
  97373. oldImp1 = norImp;
  97374. newImp1 = (rvn - c.norTar) * c.norDen;
  97375. norImp += newImp1;
  97376. if (norImp > 0) norImp = 0;
  97377. newImp1 = norImp - oldImp1;
  97378. lv1x += c.norU1X * newImp1;
  97379. lv1y += c.norU1Y * newImp1;
  97380. lv1z += c.norU1Z * newImp1;
  97381. av1x += c.norTU1X * newImp1;
  97382. av1y += c.norTU1Y * newImp1;
  97383. av1z += c.norTU1Z * newImp1;
  97384. lv2x -= c.norU2X * newImp1;
  97385. lv2y -= c.norU2Y * newImp1;
  97386. lv2z -= c.norU2Z * newImp1;
  97387. av2x -= c.norTU2X * newImp1;
  97388. av2y -= c.norTU2Y * newImp1;
  97389. av2z -= c.norTU2Z * newImp1;
  97390. c.norImp = norImp;
  97391. c.tanImp = tanImp;
  97392. c.binImp = binImp;
  97393. if (c.last) break;
  97394. c = c.next;
  97395. }
  97396. this.lv1.x = lv1x;
  97397. this.lv1.y = lv1y;
  97398. this.lv1.z = lv1z;
  97399. this.lv2.x = lv2x;
  97400. this.lv2.y = lv2y;
  97401. this.lv2.z = lv2z;
  97402. this.av1.x = av1x;
  97403. this.av1.y = av1y;
  97404. this.av1.z = av1z;
  97405. this.av2.x = av2x;
  97406. this.av2.y = av2y;
  97407. this.av2.z = av2z;
  97408. }
  97409. OIMO.ContactConstraint.prototype.postSolve = function () {
  97410. var c = this.cs;
  97411. var i = this.num;
  97412. while (i--) {
  97413. //for(var i=0;i<this.num;i++){
  97414. var p = this.ps[i];
  97415. p.normal.x = c.norX;
  97416. p.normal.y = c.norY;
  97417. p.normal.z = c.norZ;
  97418. p.tangent.x = c.tanX;
  97419. p.tangent.y = c.tanY;
  97420. p.tangent.z = c.tanZ;
  97421. p.binormal.x = c.binX;
  97422. p.binormal.y = c.binY;
  97423. p.binormal.z = c.binZ;
  97424. p.normalImpulse = c.norImp;
  97425. p.tangentImpulse = c.tanImp;
  97426. p.binormalImpulse = c.binImp;
  97427. p.normalDenominator = c.norDen;
  97428. p.tangentDenominator = c.tanDen;
  97429. p.binormalDenominator = c.binDen;
  97430. c = c.next;
  97431. }
  97432. }
  97433. /**
  97434. * A link list of contacts.
  97435. * @author saharan
  97436. */
  97437. OIMO.ContactLink = function (contact) {
  97438. // The previous contact link.
  97439. this.prev = null;
  97440. // The next contact link.
  97441. this.next = null;
  97442. // The shape of the contact.
  97443. this.shape = null;
  97444. // The other rigid body.
  97445. this.body = null;
  97446. // The contact of the link.
  97447. this.contact = contact;
  97448. }
  97449. /**
  97450. * A contact manifold between two shapes.
  97451. * @author saharan
  97452. */
  97453. OIMO.ContactManifold = function () {
  97454. // The first rigid body.
  97455. this.body1 = null;
  97456. // The second rigid body.
  97457. this.body2 = null;
  97458. // The number of manifold points.
  97459. this.numPoints = 0;
  97460. // The manifold points.
  97461. this.points = [];
  97462. this.points.length = 4;
  97463. this.points[0] = new OIMO.ManifoldPoint();
  97464. this.points[1] = new OIMO.ManifoldPoint();
  97465. this.points[2] = new OIMO.ManifoldPoint();
  97466. this.points[3] = new OIMO.ManifoldPoint();
  97467. }
  97468. OIMO.ContactManifold.prototype = {
  97469. constructor: OIMO.ContactManifold,
  97470. /**
  97471. * Reset the manifold.
  97472. * @param shape1
  97473. * @param shape2
  97474. */
  97475. reset: function (shape1, shape2) {
  97476. this.body1 = shape1.parent;
  97477. this.body2 = shape2.parent;
  97478. this.numPoints = 0;
  97479. },
  97480. /**
  97481. * Add a point into this manifold.
  97482. * @param x
  97483. * @param y
  97484. * @param z
  97485. * @param normalX
  97486. * @param normalY
  97487. * @param normalZ
  97488. * @param penetration
  97489. * @param flip
  97490. */
  97491. addPoint: function (x, y, z, normalX, normalY, normalZ, penetration, flip) {
  97492. var p = this.points[this.numPoints++];
  97493. p.position.x = x;
  97494. p.position.y = y;
  97495. p.position.z = z;
  97496. var r = this.body1.rotation;
  97497. var rx = x - this.body1.position.x;
  97498. var ry = y - this.body1.position.y;
  97499. var rz = z - this.body1.position.z;
  97500. var tr = r.elements;
  97501. p.localPoint1.x = rx * tr[0] + ry * tr[3] + rz * tr[6];
  97502. p.localPoint1.y = rx * tr[1] + ry * tr[4] + rz * tr[7];
  97503. p.localPoint1.z = rx * tr[2] + ry * tr[5] + rz * tr[8];
  97504. r = this.body2.rotation;
  97505. rx = x - this.body2.position.x;
  97506. ry = y - this.body2.position.y;
  97507. rz = z - this.body2.position.z;
  97508. p.localPoint2.x = rx * tr[0] + ry * tr[3] + rz * tr[6];
  97509. p.localPoint2.y = rx * tr[1] + ry * tr[4] + rz * tr[7];
  97510. p.localPoint2.z = rx * tr[2] + ry * tr[5] + rz * tr[8];
  97511. p.normalImpulse = 0;
  97512. if (flip) {
  97513. p.normal.x = -normalX;
  97514. p.normal.y = -normalY;
  97515. p.normal.z = -normalZ;
  97516. } else {
  97517. p.normal.x = normalX;
  97518. p.normal.y = normalY;
  97519. p.normal.z = normalZ;
  97520. }
  97521. p.penetration = penetration;
  97522. p.warmStarted = false;
  97523. }
  97524. }
  97525. OIMO.ContactPointDataBuffer = function () {
  97526. this.norX = NaN;
  97527. this.norY = NaN;
  97528. this.norZ = NaN;
  97529. this.tanX = NaN;
  97530. this.tanY = NaN;
  97531. this.tanZ = NaN;
  97532. this.binX = NaN;
  97533. this.binY = NaN;
  97534. this.binZ = NaN;
  97535. this.rp1X = NaN;
  97536. this.rp1Y = NaN;
  97537. this.rp1Z = NaN;
  97538. this.rp2X = NaN;
  97539. this.rp2Y = NaN;
  97540. this.rp2Z = NaN;
  97541. this.norU1X = NaN;
  97542. this.norU1Y = NaN;
  97543. this.norU1Z = NaN;
  97544. this.norU2X = NaN;
  97545. this.norU2Y = NaN;
  97546. this.norU2Z = NaN;
  97547. this.tanU1X = NaN;
  97548. this.tanU1Y = NaN;
  97549. this.tanU1Z = NaN;
  97550. this.tanU2X = NaN;
  97551. this.tanU2Y = NaN;
  97552. this.tanU2Z = NaN;
  97553. this.binU1X = NaN;
  97554. this.binU1Y = NaN;
  97555. this.binU1Z = NaN;
  97556. this.binU2X = NaN;
  97557. this.binU2Y = NaN;
  97558. this.binU2Z = NaN;
  97559. this.norT1X = NaN;
  97560. this.norT1Y = NaN;
  97561. this.norT1Z = NaN;
  97562. this.norT2X = NaN;
  97563. this.norT2Y = NaN;
  97564. this.norT2Z = NaN;
  97565. this.tanT1X = NaN;
  97566. this.tanT1Y = NaN;
  97567. this.tanT1Z = NaN;
  97568. this.tanT2X = NaN;
  97569. this.tanT2Y = NaN;
  97570. this.tanT2Z = NaN;
  97571. this.binT1X = NaN;
  97572. this.binT1Y = NaN;
  97573. this.binT1Z = NaN;
  97574. this.binT2X = NaN;
  97575. this.binT2Y = NaN;
  97576. this.binT2Z = NaN;
  97577. this.norTU1X = NaN;
  97578. this.norTU1Y = NaN;
  97579. this.norTU1Z = NaN;
  97580. this.norTU2X = NaN;
  97581. this.norTU2Y = NaN;
  97582. this.norTU2Z = NaN;
  97583. this.tanTU1X = NaN;
  97584. this.tanTU1Y = NaN;
  97585. this.tanTU1Z = NaN;
  97586. this.tanTU2X = NaN;
  97587. this.tanTU2Y = NaN;
  97588. this.tanTU2Z = NaN;
  97589. this.binTU1X = NaN;
  97590. this.binTU1Y = NaN;
  97591. this.binTU1Z = NaN;
  97592. this.binTU2X = NaN;
  97593. this.binTU2Y = NaN;
  97594. this.binTU2Z = NaN;
  97595. this.norImp = NaN;
  97596. this.tanImp = NaN;
  97597. this.binImp = NaN;
  97598. this.norDen = NaN;
  97599. this.tanDen = NaN;
  97600. this.binDen = NaN;
  97601. this.norTar = NaN;
  97602. this.next = null;
  97603. this.last = false;
  97604. }
  97605. OIMO.ImpulseDataBuffer = function () {
  97606. this.lp1X = NaN;
  97607. this.lp1Y = NaN;
  97608. this.lp1Z = NaN;
  97609. this.lp2X = NaN;
  97610. this.lp2Y = NaN;
  97611. this.lp2Z = NaN;
  97612. this.impulse = NaN;
  97613. }
  97614. /**
  97615. * The class holds details of the contact point.
  97616. * @author saharan
  97617. */
  97618. OIMO.ManifoldPoint = function () {
  97619. // Whether this manifold point is persisting or not.
  97620. this.warmStarted = false;
  97621. // The position of this manifold point.
  97622. this.position = new OIMO.Vec3();
  97623. // The position in the first shape's coordinate.
  97624. this.localPoint1 = new OIMO.Vec3();
  97625. // The position in the second shape's coordinate.
  97626. this.localPoint2 = new OIMO.Vec3();
  97627. // The normal vector of this manifold point.
  97628. this.normal = new OIMO.Vec3();
  97629. // The tangent vector of this manifold point.
  97630. this.tangent = new OIMO.Vec3();
  97631. // The binormal vector of this manifold point.
  97632. this.binormal = new OIMO.Vec3();
  97633. // The impulse in normal direction.
  97634. this.normalImpulse = 0;
  97635. // The impulse in tangent direction.
  97636. this.tangentImpulse = 0;
  97637. // The impulse in binormal direction.
  97638. this.binormalImpulse = 0;
  97639. // The denominator in normal direction.
  97640. this.normalDenominator = 0;
  97641. // The denominator in tangent direction.
  97642. this.tangentDenominator = 0;
  97643. // The denominator in binormal direction.
  97644. this.binormalDenominator = 0;
  97645. // The depth of penetration.
  97646. this.penetration = 0;
  97647. }
  97648. /**
  97649. * This class holds mass information of a shape.
  97650. * @author saharan
  97651. */
  97652. OIMO.MassInfo = function () {
  97653. // Mass of the shape.
  97654. this.mass = 0;
  97655. // The moment inertia of the shape.
  97656. this.inertia = new OIMO.Mat33();
  97657. };
  97658. /**
  97659. * A shape is used to detect collisions of rigid bodies.
  97660. * @author saharan
  97661. * @author lo-th
  97662. */
  97663. OIMO.Shape = function (config) {
  97664. this.type = OIMO.SHAPE_NULL;
  97665. // The global identification of the shape should be unique to the shape.
  97666. this.id = OIMO.nextID++;
  97667. // The previous shape in parent rigid body.
  97668. this.prev = null;
  97669. // The next shape in parent rigid body.
  97670. this.next = null;
  97671. // The proxy of the shape used for broad-phase collision detection.
  97672. this.proxy = null;
  97673. // The parent rigid body of the shape.
  97674. this.parent = null;
  97675. // The linked list of the contacts with the shape.
  97676. this.contactLink = null;
  97677. // The number of the contacts with the shape.
  97678. this.numContacts = 0;
  97679. // The center of gravity of the shape in world coordinate system.
  97680. this.position = new OIMO.Vec3();
  97681. // The rotation matrix of the shape in world coordinate system
  97682. this.rotation = new OIMO.Mat33();
  97683. // The position of the shape in parent's coordinate system.
  97684. this.relativePosition = new OIMO.Vec3().copy(config.relativePosition);
  97685. // The rotation matrix of the shape in parent's coordinate system.
  97686. this.relativeRotation = new OIMO.Mat33().copy(config.relativeRotation);
  97687. // The axis-aligned bounding box of the shape.
  97688. this.aabb = new OIMO.AABB();
  97689. // The density of the shape.
  97690. this.density = config.density;
  97691. // The coefficient of friction of the shape.
  97692. this.friction = config.friction;
  97693. // The coefficient of restitution of the shape.
  97694. this.restitution = config.restitution;
  97695. // The bits of the collision groups to which the shape belongs.
  97696. this.belongsTo = config.belongsTo;
  97697. // The bits of the collision groups with which the shape collides.
  97698. this.collidesWith = config.collidesWith;
  97699. };
  97700. OIMO.Shape.prototype = {
  97701. constructor: OIMO.Shape,
  97702. // Calculate the mass information of the shape.
  97703. calculateMassInfo: function (out) {
  97704. OIMO.Error("Shape", "Inheritance error.");
  97705. },
  97706. // Update the proxy of the shape.
  97707. updateProxy: function () {
  97708. OIMO.Error("Shape", "Inheritance error.");
  97709. }
  97710. };
  97711. /**
  97712. * A shape configuration holds common configuration data for constructing a shape.
  97713. * Shape configurations can be reused safely.
  97714. * @author saharan
  97715. */
  97716. OIMO.ShapeConfig = function () {
  97717. // The position of the shape in parent's coordinate system.
  97718. this.relativePosition = new OIMO.Vec3();
  97719. // The rotation matrix of the shape in parent's coordinate system.
  97720. this.relativeRotation = new OIMO.Mat33();
  97721. // The coefficient of friction of the shape.
  97722. this.friction = 0.4;
  97723. // The coefficient of restitution of the shape.
  97724. this.restitution = 0.2;
  97725. // The density of the shape.
  97726. this.density = 1;
  97727. // The bits of the collision groups to which the shape belongs.
  97728. this.belongsTo = 1;
  97729. // The bits of the collision groups with which the shape collides.
  97730. this.collidesWith = 0xffffffff;
  97731. };
  97732. /**
  97733. * A box shape.
  97734. * @author saharan
  97735. * @author lo-th
  97736. */
  97737. OIMO.BoxShape = function (config, Width, Height, Depth) {
  97738. OIMO.Shape.call(this, config);
  97739. this.type = OIMO.SHAPE_BOX;
  97740. // The width of the box.
  97741. this.width = Width;
  97742. // The height of the box.
  97743. this.height = Height;
  97744. // The depth of the box.
  97745. this.depth = Depth;
  97746. // The half-width of the box.
  97747. this.halfWidth = Width * 0.5;
  97748. // The half-height of the box.
  97749. this.halfHeight = Height * 0.5;
  97750. // The half-depth of the box.
  97751. this.halfDepth = Depth * 0.5;
  97752. this.dimentions = new OIMO_ARRAY_TYPE(18);
  97753. this.elements = new OIMO_ARRAY_TYPE(24);
  97754. };
  97755. OIMO.BoxShape.prototype = Object.create(OIMO.Shape.prototype);
  97756. OIMO.BoxShape.prototype.constructor = OIMO.BoxShape;
  97757. OIMO.BoxShape.prototype.calculateMassInfo = function (out) {
  97758. var mass = this.width * this.height * this.depth * this.density;
  97759. var divid = 1 / 12;
  97760. out.mass = mass;
  97761. out.inertia.set(
  97762. mass * (this.height * this.height + this.depth * this.depth) * divid, 0, 0,
  97763. 0, mass * (this.width * this.width + this.depth * this.depth) * divid, 0,
  97764. 0, 0, mass * (this.width * this.width + this.height * this.height) * divid
  97765. );
  97766. };
  97767. OIMO.BoxShape.prototype.updateProxy = function () {
  97768. var te = this.rotation.elements;
  97769. var di = this.dimentions;
  97770. // Width
  97771. di[0] = te[0];
  97772. di[1] = te[3];
  97773. di[2] = te[6];
  97774. // Height
  97775. di[3] = te[1];
  97776. di[4] = te[4];
  97777. di[5] = te[7];
  97778. // Depth
  97779. di[6] = te[2];
  97780. di[7] = te[5];
  97781. di[8] = te[8];
  97782. // halp Width
  97783. di[9] = te[0] * this.halfWidth;
  97784. di[10] = te[3] * this.halfWidth;
  97785. di[11] = te[6] * this.halfWidth;
  97786. // halp Height
  97787. di[12] = te[1] * this.halfHeight;
  97788. di[13] = te[4] * this.halfHeight;
  97789. di[14] = te[7] * this.halfHeight;
  97790. // halp Depth
  97791. di[15] = te[2] * this.halfDepth;
  97792. di[16] = te[5] * this.halfDepth;
  97793. di[17] = te[8] * this.halfDepth;
  97794. var wx = di[9];
  97795. var wy = di[10];
  97796. var wz = di[11];
  97797. var hx = di[12];
  97798. var hy = di[13];
  97799. var hz = di[14];
  97800. var dx = di[15];
  97801. var dy = di[16];
  97802. var dz = di[17];
  97803. var x = this.position.x;
  97804. var y = this.position.y;
  97805. var z = this.position.z;
  97806. var v = this.elements;
  97807. //v1
  97808. v[0] = x + wx + hx + dx;
  97809. v[1] = y + wy + hy + dy;
  97810. v[2] = z + wz + hz + dz;
  97811. //v2
  97812. v[3] = x + wx + hx - dx;
  97813. v[4] = y + wy + hy - dy;
  97814. v[5] = z + wz + hz - dz;
  97815. //v3
  97816. v[6] = x + wx - hx + dx;
  97817. v[7] = y + wy - hy + dy;
  97818. v[8] = z + wz - hz + dz;
  97819. //v4
  97820. v[9] = x + wx - hx - dx;
  97821. v[10] = y + wy - hy - dy;
  97822. v[11] = z + wz - hz - dz;
  97823. //v5
  97824. v[12] = x - wx + hx + dx;
  97825. v[13] = y - wy + hy + dy;
  97826. v[14] = z - wz + hz + dz;
  97827. //v6
  97828. v[15] = x - wx + hx - dx;
  97829. v[16] = y - wy + hy - dy;
  97830. v[17] = z - wz + hz - dz;
  97831. //v7
  97832. v[18] = x - wx - hx + dx;
  97833. v[19] = y - wy - hy + dy;
  97834. v[20] = z - wz - hz + dz;
  97835. //v8
  97836. v[21] = x - wx - hx - dx;
  97837. v[22] = y - wy - hy - dy;
  97838. v[23] = z - wz - hz - dz;
  97839. var w = di[9] < 0 ? -di[9] : di[9];
  97840. var h = di[10] < 0 ? -di[10] : di[10];
  97841. var d = di[11] < 0 ? -di[11] : di[11];
  97842. w = di[12] < 0 ? w - di[12] : w + di[12];
  97843. h = di[13] < 0 ? h - di[13] : h + di[13];
  97844. d = di[14] < 0 ? d - di[14] : d + di[14];
  97845. w = di[15] < 0 ? w - di[15] : w + di[15];
  97846. h = di[16] < 0 ? h - di[16] : h + di[16];
  97847. d = di[17] < 0 ? d - di[17] : d + di[17];
  97848. var p = OIMO.AABB_PROX;
  97849. this.aabb.set(
  97850. this.position.x - w - p, this.position.x + w + p,
  97851. this.position.y - h - p, this.position.y + h + p,
  97852. this.position.z - d - p, this.position.z + d + p
  97853. );
  97854. if (this.proxy != null) this.proxy.update();
  97855. };
  97856. /**
  97857. * A sphere shape.
  97858. * @author saharan
  97859. * @author lo-th
  97860. */
  97861. OIMO.SphereShape = function (config, radius) {
  97862. OIMO.Shape.call(this, config);
  97863. this.type = OIMO.SHAPE_SPHERE;
  97864. // The radius of the shape.
  97865. this.radius = radius;
  97866. };
  97867. OIMO.SphereShape.prototype = Object.create(OIMO.Shape.prototype);
  97868. OIMO.SphereShape.prototype.constructor = OIMO.SphereShape;
  97869. OIMO.SphereShape.prototype.calculateMassInfo = function (out) {
  97870. var mass = 1.333 * OIMO.PI * this.radius * this.radius * this.radius * this.density;
  97871. out.mass = mass;
  97872. var inertia = mass * this.radius * this.radius * 0.4;
  97873. out.inertia.set(inertia, 0, 0, 0, inertia, 0, 0, 0, inertia);
  97874. };
  97875. OIMO.SphereShape.prototype.updateProxy = function () {
  97876. var p = OIMO.AABB_PROX;
  97877. this.aabb.set(
  97878. this.position.x - this.radius - p, this.position.x + this.radius + p,
  97879. this.position.y - this.radius - p, this.position.y + this.radius + p,
  97880. this.position.z - this.radius - p, this.position.z + this.radius + p
  97881. );
  97882. if (this.proxy != null) this.proxy.update();
  97883. };
  97884. /**
  97885. * A cylinder shap.
  97886. * @author saharan
  97887. * @author lo-th
  97888. */
  97889. OIMO.CylinderShape = function (config, radius, height) {
  97890. OIMO.Shape.call(this, config);
  97891. this.type = OIMO.SHAPE_CYLINDER;
  97892. this.radius = radius;
  97893. this.height = height;
  97894. this.halfHeight = height * 0.5;
  97895. this.normalDirection = new OIMO.Vec3();
  97896. this.halfDirection = new OIMO.Vec3();
  97897. };
  97898. OIMO.CylinderShape.prototype = Object.create(OIMO.Shape.prototype);
  97899. OIMO.CylinderShape.prototype.constructor = OIMO.CylinderShape;
  97900. OIMO.CylinderShape.prototype.calculateMassInfo = function (out) {
  97901. var rsq = this.radius * this.radius;
  97902. var mass = OIMO.PI * rsq * this.height * this.density;
  97903. var inertiaXZ = ((0.25 * rsq) + (0.0833 * this.height * this.height)) * mass;
  97904. var inertiaY = 0.5 * rsq;
  97905. out.mass = mass;
  97906. out.inertia.set(inertiaXZ, 0, 0, 0, inertiaY, 0, 0, 0, inertiaXZ);
  97907. };
  97908. OIMO.CylinderShape.prototype.updateProxy = function () {
  97909. var te = this.rotation.elements;
  97910. var len, wx, hy, dz, xx, yy, zz, w, h, d, p;
  97911. xx = te[1] * te[1];
  97912. yy = te[4] * te[4];
  97913. zz = te[7] * te[7];
  97914. this.normalDirection.set(te[1], te[4], te[7]);
  97915. this.halfDirection.scale(this.normalDirection, this.halfHeight);
  97916. wx = 1 - xx;
  97917. len = OIMO.sqrt(wx * wx + xx * yy + xx * zz);
  97918. if (len > 0) len = this.radius / len;
  97919. wx *= len;
  97920. hy = 1 - yy;
  97921. len = OIMO.sqrt(yy * xx + hy * hy + yy * zz);
  97922. if (len > 0) len = this.radius / len;
  97923. hy *= len;
  97924. dz = 1 - zz;
  97925. len = OIMO.sqrt(zz * xx + zz * yy + dz * dz);
  97926. if (len > 0) len = this.radius / len;
  97927. dz *= len;
  97928. w = this.halfDirection.x < 0 ? -this.halfDirection.x : this.halfDirection.x;
  97929. h = this.halfDirection.y < 0 ? -this.halfDirection.y : this.halfDirection.y;
  97930. d = this.halfDirection.z < 0 ? -this.halfDirection.z : this.halfDirection.z;
  97931. w = wx < 0 ? w - wx : w + wx;
  97932. h = hy < 0 ? h - hy : h + hy;
  97933. d = dz < 0 ? d - dz : d + dz;
  97934. p = OIMO.AABB_PROX;
  97935. this.aabb.set(
  97936. this.position.x - w - p, this.position.x + w + p,
  97937. this.position.y - h - p, this.position.y + h + p,
  97938. this.position.z - d - p, this.position.z + d + p
  97939. );
  97940. if (this.proxy != null) this.proxy.update();
  97941. };
  97942. /**
  97943. * A tetra shape.
  97944. * @author xprogram
  97945. */
  97946. OIMO.TetraShape = function (config, p1, p2, p3, p4) {
  97947. OIMO.Shape.call(this, config);
  97948. this.type = OIMO.SHAPE_TETRA;
  97949. // Vertices and faces of tetra
  97950. this.verts = [p1, p2, p3, p4];
  97951. this.faces = [
  97952. mtri(0, 1, 2),
  97953. mtri(1, 2, 3),
  97954. mtri(2, 3, 4),
  97955. mtri(4, 0, 1),
  97956. ];
  97957. };
  97958. OIMO.TetraShape.prototype = Object.create(OIMO.Shape.prototype);
  97959. OIMO.TetraShape.prototype.constructor = OIMO.TetraShape;
  97960. OIMO.TetraShape.prototype.calculateMassInfo = function () {
  97961. // I guess you could calculate box mass and split it
  97962. // in half for the tetra...
  97963. };
  97964. OIMO.TetraShape.prototype.updateProxy = function () {
  97965. this.aabb.setFromPoints(this.verts);
  97966. if (this.proxy !== null)
  97967. this.proxy.update();
  97968. };
  97969. function mtri(a, b, c) {
  97970. return { a: a, b: b, c: c };
  97971. }
  97972. OIMO.CollisionDetector = function () {
  97973. this.flip = false;
  97974. };
  97975. OIMO.CollisionDetector.prototype = {
  97976. constructor: OIMO.CollisionDetector,
  97977. detectCollision: function (shape1, shape2, manifold) {
  97978. OIMO.Error("CollisionDetector", "Inheritance error.");
  97979. }
  97980. };
  97981. /**
  97982. * A collision detector which detects collisions between two boxes.
  97983. * @author saharan
  97984. */
  97985. OIMO.BoxBoxCollisionDetector = function () {
  97986. OIMO.CollisionDetector.call(this);
  97987. this.clipVertices1 = new OIMO_ARRAY_TYPE(24); // 8 vertices x,y,z
  97988. this.clipVertices2 = new OIMO_ARRAY_TYPE(24);
  97989. this.used = new OIMO_ARRAY_TYPE(8);
  97990. this.INF = 1 / 0;
  97991. };
  97992. OIMO.BoxBoxCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  97993. OIMO.BoxBoxCollisionDetector.prototype.constructor = OIMO.BoxBoxCollisionDetector;
  97994. OIMO.BoxBoxCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  97995. // What you are doing
  97996. // · I to prepare a separate axis of the fifteen
  97997. //-Six in each of three normal vectors of the xyz direction of the box both
  97998. // · Remaining nine 3x3 a vector perpendicular to the side of the box 2 and the side of the box 1
  97999. // · Calculate the depth to the separation axis
  98000. // Calculates the distance using the inner product and put the amount of embedment
  98001. // · However a vertical separation axis and side to weight a little to avoid vibration
  98002. // And end when there is a separate axis that is remote even one
  98003. // · I look for separation axis with little to dent most
  98004. // Men and if separation axis of the first six - end collision
  98005. // Heng If it separate axis of nine other - side collision
  98006. // Heng - case of a side collision
  98007. // · Find points of two sides on which you made ​​the separation axis
  98008. // Calculates the point of closest approach of a straight line consisting of separate axis points obtained, and the collision point
  98009. //-Surface - the case of the plane crash
  98010. //-Box A, box B and the other a box of better made ​​a separate axis
  98011. // • 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
  98012. // When viewed from the front surface A, and the cut part exceeding the area of the surface A is a surface B
  98013. //-Plane B becomes the 3-8 triangle, I a candidate for the collision point the vertex of surface B
  98014. // • If more than one candidate 5 exists, scraping up to four
  98015. // For potential collision points of all, to examine the distance between the surface A
  98016. // • If you were on the inside surface of A, and the collision point
  98017. var b1;
  98018. var b2;
  98019. if (shape1.id < shape2.id) {
  98020. b1 = (shape1);
  98021. b2 = (shape2);
  98022. } else {
  98023. b1 = (shape2);
  98024. b2 = (shape1);
  98025. }
  98026. var V1 = b1.elements;
  98027. var V2 = b2.elements;
  98028. var D1 = b1.dimentions;
  98029. var D2 = b2.dimentions;
  98030. var p1 = b1.position;
  98031. var p2 = b2.position;
  98032. var p1x = p1.x;
  98033. var p1y = p1.y;
  98034. var p1z = p1.z;
  98035. var p2x = p2.x;
  98036. var p2y = p2.y;
  98037. var p2z = p2.z;
  98038. // diff
  98039. var dx = p2x - p1x;
  98040. var dy = p2y - p1y;
  98041. var dz = p2z - p1z;
  98042. // distance
  98043. var w1 = b1.halfWidth;
  98044. var h1 = b1.halfHeight;
  98045. var d1 = b1.halfDepth;
  98046. var w2 = b2.halfWidth;
  98047. var h2 = b2.halfHeight;
  98048. var d2 = b2.halfDepth;
  98049. // direction
  98050. // ----------------------------
  98051. // 15 separating axes
  98052. // 1~6: face
  98053. // 7~f: edge
  98054. // http://marupeke296.com/COL_3D_No13_OBBvsOBB.html
  98055. // ----------------------------
  98056. var a1x = D1[0];
  98057. var a1y = D1[1];
  98058. var a1z = D1[2];
  98059. var a2x = D1[3];
  98060. var a2y = D1[4];
  98061. var a2z = D1[5];
  98062. var a3x = D1[6];
  98063. var a3y = D1[7];
  98064. var a3z = D1[8];
  98065. var d1x = D1[9];
  98066. var d1y = D1[10];
  98067. var d1z = D1[11];
  98068. var d2x = D1[12];
  98069. var d2y = D1[13];
  98070. var d2z = D1[14];
  98071. var d3x = D1[15];
  98072. var d3y = D1[16];
  98073. var d3z = D1[17];
  98074. var a4x = D2[0];
  98075. var a4y = D2[1];
  98076. var a4z = D2[2];
  98077. var a5x = D2[3];
  98078. var a5y = D2[4];
  98079. var a5z = D2[5];
  98080. var a6x = D2[6];
  98081. var a6y = D2[7];
  98082. var a6z = D2[8];
  98083. var d4x = D2[9];
  98084. var d4y = D2[10];
  98085. var d4z = D2[11];
  98086. var d5x = D2[12];
  98087. var d5y = D2[13];
  98088. var d5z = D2[14];
  98089. var d6x = D2[15];
  98090. var d6y = D2[16];
  98091. var d6z = D2[17];
  98092. var a7x = a1y * a4z - a1z * a4y;
  98093. var a7y = a1z * a4x - a1x * a4z;
  98094. var a7z = a1x * a4y - a1y * a4x;
  98095. var a8x = a1y * a5z - a1z * a5y;
  98096. var a8y = a1z * a5x - a1x * a5z;
  98097. var a8z = a1x * a5y - a1y * a5x;
  98098. var a9x = a1y * a6z - a1z * a6y;
  98099. var a9y = a1z * a6x - a1x * a6z;
  98100. var a9z = a1x * a6y - a1y * a6x;
  98101. var aax = a2y * a4z - a2z * a4y;
  98102. var aay = a2z * a4x - a2x * a4z;
  98103. var aaz = a2x * a4y - a2y * a4x;
  98104. var abx = a2y * a5z - a2z * a5y;
  98105. var aby = a2z * a5x - a2x * a5z;
  98106. var abz = a2x * a5y - a2y * a5x;
  98107. var acx = a2y * a6z - a2z * a6y;
  98108. var acy = a2z * a6x - a2x * a6z;
  98109. var acz = a2x * a6y - a2y * a6x;
  98110. var adx = a3y * a4z - a3z * a4y;
  98111. var ady = a3z * a4x - a3x * a4z;
  98112. var adz = a3x * a4y - a3y * a4x;
  98113. var aex = a3y * a5z - a3z * a5y;
  98114. var aey = a3z * a5x - a3x * a5z;
  98115. var aez = a3x * a5y - a3y * a5x;
  98116. var afx = a3y * a6z - a3z * a6y;
  98117. var afy = a3z * a6x - a3x * a6z;
  98118. var afz = a3x * a6y - a3y * a6x;
  98119. // right or left flags
  98120. var right1;
  98121. var right2;
  98122. var right3;
  98123. var right4;
  98124. var right5;
  98125. var right6;
  98126. var right7;
  98127. var right8;
  98128. var right9;
  98129. var righta;
  98130. var rightb;
  98131. var rightc;
  98132. var rightd;
  98133. var righte;
  98134. var rightf;
  98135. // overlapping distances
  98136. var overlap1;
  98137. var overlap2;
  98138. var overlap3;
  98139. var overlap4;
  98140. var overlap5;
  98141. var overlap6;
  98142. var overlap7;
  98143. var overlap8;
  98144. var overlap9;
  98145. var overlapa;
  98146. var overlapb;
  98147. var overlapc;
  98148. var overlapd;
  98149. var overlape;
  98150. var overlapf;
  98151. // invalid flags
  98152. var invalid7 = false;
  98153. var invalid8 = false;
  98154. var invalid9 = false;
  98155. var invalida = false;
  98156. var invalidb = false;
  98157. var invalidc = false;
  98158. var invalidd = false;
  98159. var invalide = false;
  98160. var invalidf = false;
  98161. // temporary variables
  98162. var len;
  98163. var len1;
  98164. var len2;
  98165. var dot1;
  98166. var dot2;
  98167. var dot3;
  98168. // try axis 1
  98169. len = a1x * dx + a1y * dy + a1z * dz;
  98170. right1 = len > 0;
  98171. if (!right1) len = -len;
  98172. len1 = w1;
  98173. dot1 = a1x * a4x + a1y * a4y + a1z * a4z;
  98174. dot2 = a1x * a5x + a1y * a5y + a1z * a5z;
  98175. dot3 = a1x * a6x + a1y * a6y + a1z * a6z;
  98176. if (dot1 < 0) dot1 = -dot1;
  98177. if (dot2 < 0) dot2 = -dot2;
  98178. if (dot3 < 0) dot3 = -dot3;
  98179. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  98180. overlap1 = len - len1 - len2;
  98181. if (overlap1 > 0) return;
  98182. // try axis 2
  98183. len = a2x * dx + a2y * dy + a2z * dz;
  98184. right2 = len > 0;
  98185. if (!right2) len = -len;
  98186. len1 = h1;
  98187. dot1 = a2x * a4x + a2y * a4y + a2z * a4z;
  98188. dot2 = a2x * a5x + a2y * a5y + a2z * a5z;
  98189. dot3 = a2x * a6x + a2y * a6y + a2z * a6z;
  98190. if (dot1 < 0) dot1 = -dot1;
  98191. if (dot2 < 0) dot2 = -dot2;
  98192. if (dot3 < 0) dot3 = -dot3;
  98193. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  98194. overlap2 = len - len1 - len2;
  98195. if (overlap2 > 0) return;
  98196. // try axis 3
  98197. len = a3x * dx + a3y * dy + a3z * dz;
  98198. right3 = len > 0;
  98199. if (!right3) len = -len;
  98200. len1 = d1;
  98201. dot1 = a3x * a4x + a3y * a4y + a3z * a4z;
  98202. dot2 = a3x * a5x + a3y * a5y + a3z * a5z;
  98203. dot3 = a3x * a6x + a3y * a6y + a3z * a6z;
  98204. if (dot1 < 0) dot1 = -dot1;
  98205. if (dot2 < 0) dot2 = -dot2;
  98206. if (dot3 < 0) dot3 = -dot3;
  98207. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  98208. overlap3 = len - len1 - len2;
  98209. if (overlap3 > 0) return;
  98210. // try axis 4
  98211. len = a4x * dx + a4y * dy + a4z * dz;
  98212. right4 = len > 0;
  98213. if (!right4) len = -len;
  98214. dot1 = a4x * a1x + a4y * a1y + a4z * a1z;
  98215. dot2 = a4x * a2x + a4y * a2y + a4z * a2z;
  98216. dot3 = a4x * a3x + a4y * a3y + a4z * a3z;
  98217. if (dot1 < 0) dot1 = -dot1;
  98218. if (dot2 < 0) dot2 = -dot2;
  98219. if (dot3 < 0) dot3 = -dot3;
  98220. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  98221. len2 = w2;
  98222. overlap4 = (len - len1 - len2) * 1.0;
  98223. if (overlap4 > 0) return;
  98224. // try axis 5
  98225. len = a5x * dx + a5y * dy + a5z * dz;
  98226. right5 = len > 0;
  98227. if (!right5) len = -len;
  98228. dot1 = a5x * a1x + a5y * a1y + a5z * a1z;
  98229. dot2 = a5x * a2x + a5y * a2y + a5z * a2z;
  98230. dot3 = a5x * a3x + a5y * a3y + a5z * a3z;
  98231. if (dot1 < 0) dot1 = -dot1;
  98232. if (dot2 < 0) dot2 = -dot2;
  98233. if (dot3 < 0) dot3 = -dot3;
  98234. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  98235. len2 = h2;
  98236. overlap5 = (len - len1 - len2) * 1.0;
  98237. if (overlap5 > 0) return;
  98238. // try axis 6
  98239. len = a6x * dx + a6y * dy + a6z * dz;
  98240. right6 = len > 0;
  98241. if (!right6) len = -len;
  98242. dot1 = a6x * a1x + a6y * a1y + a6z * a1z;
  98243. dot2 = a6x * a2x + a6y * a2y + a6z * a2z;
  98244. dot3 = a6x * a3x + a6y * a3y + a6z * a3z;
  98245. if (dot1 < 0) dot1 = -dot1;
  98246. if (dot2 < 0) dot2 = -dot2;
  98247. if (dot3 < 0) dot3 = -dot3;
  98248. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  98249. len2 = d2;
  98250. overlap6 = (len - len1 - len2) * 1.0;
  98251. if (overlap6 > 0) return;
  98252. // try axis 7
  98253. len = a7x * a7x + a7y * a7y + a7z * a7z;
  98254. if (len > 1e-5) {
  98255. len = 1 / OIMO.sqrt(len);
  98256. a7x *= len;
  98257. a7y *= len;
  98258. a7z *= len;
  98259. len = a7x * dx + a7y * dy + a7z * dz;
  98260. right7 = len > 0;
  98261. if (!right7) len = -len;
  98262. dot1 = a7x * a2x + a7y * a2y + a7z * a2z;
  98263. dot2 = a7x * a3x + a7y * a3y + a7z * a3z;
  98264. if (dot1 < 0) dot1 = -dot1;
  98265. if (dot2 < 0) dot2 = -dot2;
  98266. len1 = dot1 * h1 + dot2 * d1;
  98267. dot1 = a7x * a5x + a7y * a5y + a7z * a5z;
  98268. dot2 = a7x * a6x + a7y * a6y + a7z * a6z;
  98269. if (dot1 < 0) dot1 = -dot1;
  98270. if (dot2 < 0) dot2 = -dot2;
  98271. len2 = dot1 * h2 + dot2 * d2;
  98272. overlap7 = len - len1 - len2;
  98273. if (overlap7 > 0) return;
  98274. } else {
  98275. right7 = false;
  98276. overlap7 = 0;
  98277. invalid7 = true;
  98278. }
  98279. // try axis 8
  98280. len = a8x * a8x + a8y * a8y + a8z * a8z;
  98281. if (len > 1e-5) {
  98282. len = 1 / OIMO.sqrt(len);
  98283. a8x *= len;
  98284. a8y *= len;
  98285. a8z *= len;
  98286. len = a8x * dx + a8y * dy + a8z * dz;
  98287. right8 = len > 0;
  98288. if (!right8) len = -len;
  98289. dot1 = a8x * a2x + a8y * a2y + a8z * a2z;
  98290. dot2 = a8x * a3x + a8y * a3y + a8z * a3z;
  98291. if (dot1 < 0) dot1 = -dot1;
  98292. if (dot2 < 0) dot2 = -dot2;
  98293. len1 = dot1 * h1 + dot2 * d1;
  98294. dot1 = a8x * a4x + a8y * a4y + a8z * a4z;
  98295. dot2 = a8x * a6x + a8y * a6y + a8z * a6z;
  98296. if (dot1 < 0) dot1 = -dot1;
  98297. if (dot2 < 0) dot2 = -dot2;
  98298. len2 = dot1 * w2 + dot2 * d2;
  98299. overlap8 = len - len1 - len2;
  98300. if (overlap8 > 0) return;
  98301. } else {
  98302. right8 = false;
  98303. overlap8 = 0;
  98304. invalid8 = true;
  98305. }
  98306. // try axis 9
  98307. len = a9x * a9x + a9y * a9y + a9z * a9z;
  98308. if (len > 1e-5) {
  98309. len = 1 / OIMO.sqrt(len);
  98310. a9x *= len;
  98311. a9y *= len;
  98312. a9z *= len;
  98313. len = a9x * dx + a9y * dy + a9z * dz;
  98314. right9 = len > 0;
  98315. if (!right9) len = -len;
  98316. dot1 = a9x * a2x + a9y * a2y + a9z * a2z;
  98317. dot2 = a9x * a3x + a9y * a3y + a9z * a3z;
  98318. if (dot1 < 0) dot1 = -dot1;
  98319. if (dot2 < 0) dot2 = -dot2;
  98320. len1 = dot1 * h1 + dot2 * d1;
  98321. dot1 = a9x * a4x + a9y * a4y + a9z * a4z;
  98322. dot2 = a9x * a5x + a9y * a5y + a9z * a5z;
  98323. if (dot1 < 0) dot1 = -dot1;
  98324. if (dot2 < 0) dot2 = -dot2;
  98325. len2 = dot1 * w2 + dot2 * h2;
  98326. overlap9 = len - len1 - len2;
  98327. if (overlap9 > 0) return;
  98328. } else {
  98329. right9 = false;
  98330. overlap9 = 0;
  98331. invalid9 = true;
  98332. }
  98333. // try axis 10
  98334. len = aax * aax + aay * aay + aaz * aaz;
  98335. if (len > 1e-5) {
  98336. len = 1 / OIMO.sqrt(len);
  98337. aax *= len;
  98338. aay *= len;
  98339. aaz *= len;
  98340. len = aax * dx + aay * dy + aaz * dz;
  98341. righta = len > 0;
  98342. if (!righta) len = -len;
  98343. dot1 = aax * a1x + aay * a1y + aaz * a1z;
  98344. dot2 = aax * a3x + aay * a3y + aaz * a3z;
  98345. if (dot1 < 0) dot1 = -dot1;
  98346. if (dot2 < 0) dot2 = -dot2;
  98347. len1 = dot1 * w1 + dot2 * d1;
  98348. dot1 = aax * a5x + aay * a5y + aaz * a5z;
  98349. dot2 = aax * a6x + aay * a6y + aaz * a6z;
  98350. if (dot1 < 0) dot1 = -dot1;
  98351. if (dot2 < 0) dot2 = -dot2;
  98352. len2 = dot1 * h2 + dot2 * d2;
  98353. overlapa = len - len1 - len2;
  98354. if (overlapa > 0) return;
  98355. } else {
  98356. righta = false;
  98357. overlapa = 0;
  98358. invalida = true;
  98359. }
  98360. // try axis 11
  98361. len = abx * abx + aby * aby + abz * abz;
  98362. if (len > 1e-5) {
  98363. len = 1 / OIMO.sqrt(len);
  98364. abx *= len;
  98365. aby *= len;
  98366. abz *= len;
  98367. len = abx * dx + aby * dy + abz * dz;
  98368. rightb = len > 0;
  98369. if (!rightb) len = -len;
  98370. dot1 = abx * a1x + aby * a1y + abz * a1z;
  98371. dot2 = abx * a3x + aby * a3y + abz * a3z;
  98372. if (dot1 < 0) dot1 = -dot1;
  98373. if (dot2 < 0) dot2 = -dot2;
  98374. len1 = dot1 * w1 + dot2 * d1;
  98375. dot1 = abx * a4x + aby * a4y + abz * a4z;
  98376. dot2 = abx * a6x + aby * a6y + abz * a6z;
  98377. if (dot1 < 0) dot1 = -dot1;
  98378. if (dot2 < 0) dot2 = -dot2;
  98379. len2 = dot1 * w2 + dot2 * d2;
  98380. overlapb = len - len1 - len2;
  98381. if (overlapb > 0) return;
  98382. } else {
  98383. rightb = false;
  98384. overlapb = 0;
  98385. invalidb = true;
  98386. }
  98387. // try axis 12
  98388. len = acx * acx + acy * acy + acz * acz;
  98389. if (len > 1e-5) {
  98390. len = 1 / OIMO.sqrt(len);
  98391. acx *= len;
  98392. acy *= len;
  98393. acz *= len;
  98394. len = acx * dx + acy * dy + acz * dz;
  98395. rightc = len > 0;
  98396. if (!rightc) len = -len;
  98397. dot1 = acx * a1x + acy * a1y + acz * a1z;
  98398. dot2 = acx * a3x + acy * a3y + acz * a3z;
  98399. if (dot1 < 0) dot1 = -dot1;
  98400. if (dot2 < 0) dot2 = -dot2;
  98401. len1 = dot1 * w1 + dot2 * d1;
  98402. dot1 = acx * a4x + acy * a4y + acz * a4z;
  98403. dot2 = acx * a5x + acy * a5y + acz * a5z;
  98404. if (dot1 < 0) dot1 = -dot1;
  98405. if (dot2 < 0) dot2 = -dot2;
  98406. len2 = dot1 * w2 + dot2 * h2;
  98407. overlapc = len - len1 - len2;
  98408. if (overlapc > 0) return;
  98409. } else {
  98410. rightc = false;
  98411. overlapc = 0;
  98412. invalidc = true;
  98413. }
  98414. // try axis 13
  98415. len = adx * adx + ady * ady + adz * adz;
  98416. if (len > 1e-5) {
  98417. len = 1 / OIMO.sqrt(len);
  98418. adx *= len;
  98419. ady *= len;
  98420. adz *= len;
  98421. len = adx * dx + ady * dy + adz * dz;
  98422. rightd = len > 0;
  98423. if (!rightd) len = -len;
  98424. dot1 = adx * a1x + ady * a1y + adz * a1z;
  98425. dot2 = adx * a2x + ady * a2y + adz * a2z;
  98426. if (dot1 < 0) dot1 = -dot1;
  98427. if (dot2 < 0) dot2 = -dot2;
  98428. len1 = dot1 * w1 + dot2 * h1;
  98429. dot1 = adx * a5x + ady * a5y + adz * a5z;
  98430. dot2 = adx * a6x + ady * a6y + adz * a6z;
  98431. if (dot1 < 0) dot1 = -dot1;
  98432. if (dot2 < 0) dot2 = -dot2;
  98433. len2 = dot1 * h2 + dot2 * d2;
  98434. overlapd = len - len1 - len2;
  98435. if (overlapd > 0) return;
  98436. } else {
  98437. rightd = false;
  98438. overlapd = 0;
  98439. invalidd = true;
  98440. }
  98441. // try axis 14
  98442. len = aex * aex + aey * aey + aez * aez;
  98443. if (len > 1e-5) {
  98444. len = 1 / OIMO.sqrt(len);
  98445. aex *= len;
  98446. aey *= len;
  98447. aez *= len;
  98448. len = aex * dx + aey * dy + aez * dz;
  98449. righte = len > 0;
  98450. if (!righte) len = -len;
  98451. dot1 = aex * a1x + aey * a1y + aez * a1z;
  98452. dot2 = aex * a2x + aey * a2y + aez * a2z;
  98453. if (dot1 < 0) dot1 = -dot1;
  98454. if (dot2 < 0) dot2 = -dot2;
  98455. len1 = dot1 * w1 + dot2 * h1;
  98456. dot1 = aex * a4x + aey * a4y + aez * a4z;
  98457. dot2 = aex * a6x + aey * a6y + aez * a6z;
  98458. if (dot1 < 0) dot1 = -dot1;
  98459. if (dot2 < 0) dot2 = -dot2;
  98460. len2 = dot1 * w2 + dot2 * d2;
  98461. overlape = len - len1 - len2;
  98462. if (overlape > 0) return;
  98463. } else {
  98464. righte = false;
  98465. overlape = 0;
  98466. invalide = true;
  98467. }
  98468. // try axis 15
  98469. len = afx * afx + afy * afy + afz * afz;
  98470. if (len > 1e-5) {
  98471. len = 1 / OIMO.sqrt(len);
  98472. afx *= len;
  98473. afy *= len;
  98474. afz *= len;
  98475. len = afx * dx + afy * dy + afz * dz;
  98476. rightf = len > 0;
  98477. if (!rightf) len = -len;
  98478. dot1 = afx * a1x + afy * a1y + afz * a1z;
  98479. dot2 = afx * a2x + afy * a2y + afz * a2z;
  98480. if (dot1 < 0) dot1 = -dot1;
  98481. if (dot2 < 0) dot2 = -dot2;
  98482. len1 = dot1 * w1 + dot2 * h1;
  98483. dot1 = afx * a4x + afy * a4y + afz * a4z;
  98484. dot2 = afx * a5x + afy * a5y + afz * a5z;
  98485. if (dot1 < 0) dot1 = -dot1;
  98486. if (dot2 < 0) dot2 = -dot2;
  98487. len2 = dot1 * w2 + dot2 * h2;
  98488. overlapf = len - len1 - len2;
  98489. if (overlapf > 0) return;
  98490. } else {
  98491. rightf = false;
  98492. overlapf = 0;
  98493. invalidf = true;
  98494. }
  98495. // boxes are overlapping
  98496. var depth = overlap1;
  98497. var depth2 = overlap1;
  98498. var minIndex = 0;
  98499. var right = right1;
  98500. if (overlap2 > depth2) {
  98501. depth = overlap2;
  98502. depth2 = overlap2;
  98503. minIndex = 1;
  98504. right = right2;
  98505. }
  98506. if (overlap3 > depth2) {
  98507. depth = overlap3;
  98508. depth2 = overlap3;
  98509. minIndex = 2;
  98510. right = right3;
  98511. }
  98512. if (overlap4 > depth2) {
  98513. depth = overlap4;
  98514. depth2 = overlap4;
  98515. minIndex = 3;
  98516. right = right4;
  98517. }
  98518. if (overlap5 > depth2) {
  98519. depth = overlap5;
  98520. depth2 = overlap5;
  98521. minIndex = 4;
  98522. right = right5;
  98523. }
  98524. if (overlap6 > depth2) {
  98525. depth = overlap6;
  98526. depth2 = overlap6;
  98527. minIndex = 5;
  98528. right = right6;
  98529. }
  98530. if (overlap7 - 0.01 > depth2 && !invalid7) {
  98531. depth = overlap7;
  98532. depth2 = overlap7 - 0.01;
  98533. minIndex = 6;
  98534. right = right7;
  98535. }
  98536. if (overlap8 - 0.01 > depth2 && !invalid8) {
  98537. depth = overlap8;
  98538. depth2 = overlap8 - 0.01;
  98539. minIndex = 7;
  98540. right = right8;
  98541. }
  98542. if (overlap9 - 0.01 > depth2 && !invalid9) {
  98543. depth = overlap9;
  98544. depth2 = overlap9 - 0.01;
  98545. minIndex = 8;
  98546. right = right9;
  98547. }
  98548. if (overlapa - 0.01 > depth2 && !invalida) {
  98549. depth = overlapa;
  98550. depth2 = overlapa - 0.01;
  98551. minIndex = 9;
  98552. right = righta;
  98553. }
  98554. if (overlapb - 0.01 > depth2 && !invalidb) {
  98555. depth = overlapb;
  98556. depth2 = overlapb - 0.01;
  98557. minIndex = 10;
  98558. right = rightb;
  98559. }
  98560. if (overlapc - 0.01 > depth2 && !invalidc) {
  98561. depth = overlapc;
  98562. depth2 = overlapc - 0.01;
  98563. minIndex = 11;
  98564. right = rightc;
  98565. }
  98566. if (overlapd - 0.01 > depth2 && !invalidd) {
  98567. depth = overlapd;
  98568. depth2 = overlapd - 0.01;
  98569. minIndex = 12;
  98570. right = rightd;
  98571. }
  98572. if (overlape - 0.01 > depth2 && !invalide) {
  98573. depth = overlape;
  98574. depth2 = overlape - 0.01;
  98575. minIndex = 13;
  98576. right = righte;
  98577. }
  98578. if (overlapf - 0.01 > depth2 && !invalidf) {
  98579. depth = overlapf;
  98580. minIndex = 14;
  98581. right = rightf;
  98582. }
  98583. // normal
  98584. var nx = 0;
  98585. var ny = 0;
  98586. var nz = 0;
  98587. // edge line or face side normal
  98588. var n1x = 0;
  98589. var n1y = 0;
  98590. var n1z = 0;
  98591. var n2x = 0;
  98592. var n2y = 0;
  98593. var n2z = 0;
  98594. // center of current face
  98595. var cx = 0;
  98596. var cy = 0;
  98597. var cz = 0;
  98598. // face side
  98599. var s1x = 0;
  98600. var s1y = 0;
  98601. var s1z = 0;
  98602. var s2x = 0;
  98603. var s2y = 0;
  98604. var s2z = 0;
  98605. // swap b1 b2
  98606. var swap = false;
  98607. //_______________________________________
  98608. if (minIndex == 0) {// b1.x * b2
  98609. if (right) {
  98610. cx = p1x + d1x; cy = p1y + d1y; cz = p1z + d1z;
  98611. nx = a1x; ny = a1y; nz = a1z;
  98612. } else {
  98613. cx = p1x - d1x; cy = p1y - d1y; cz = p1z - d1z;
  98614. nx = -a1x; ny = -a1y; nz = -a1z;
  98615. }
  98616. s1x = d2x; s1y = d2y; s1z = d2z;
  98617. n1x = -a2x; n1y = -a2y; n1z = -a2z;
  98618. s2x = d3x; s2y = d3y; s2z = d3z;
  98619. n2x = -a3x; n2y = -a3y; n2z = -a3z;
  98620. }
  98621. else if (minIndex == 1) {// b1.y * b2
  98622. if (right) {
  98623. cx = p1x + d2x; cy = p1y + d2y; cz = p1z + d2z;
  98624. nx = a2x; ny = a2y; nz = a2z;
  98625. } else {
  98626. cx = p1x - d2x; cy = p1y - d2y; cz = p1z - d2z;
  98627. nx = -a2x; ny = -a2y; nz = -a2z;
  98628. }
  98629. s1x = d1x; s1y = d1y; s1z = d1z;
  98630. n1x = -a1x; n1y = -a1y; n1z = -a1z;
  98631. s2x = d3x; s2y = d3y; s2z = d3z;
  98632. n2x = -a3x; n2y = -a3y; n2z = -a3z;
  98633. }
  98634. else if (minIndex == 2) {// b1.z * b2
  98635. if (right) {
  98636. cx = p1x + d3x; cy = p1y + d3y; cz = p1z + d3z;
  98637. nx = a3x; ny = a3y; nz = a3z;
  98638. } else {
  98639. cx = p1x - d3x; cy = p1y - d3y; cz = p1z - d3z;
  98640. nx = -a3x; ny = -a3y; nz = -a3z;
  98641. }
  98642. s1x = d1x; s1y = d1y; s1z = d1z;
  98643. n1x = -a1x; n1y = -a1y; n1z = -a1z;
  98644. s2x = d2x; s2y = d2y; s2z = d2z;
  98645. n2x = -a2x; n2y = -a2y; n2z = -a2z;
  98646. }
  98647. else if (minIndex == 3) {// b2.x * b1
  98648. swap = true;
  98649. if (!right) {
  98650. cx = p2x + d4x; cy = p2y + d4y; cz = p2z + d4z;
  98651. nx = a4x; ny = a4y; nz = a4z;
  98652. } else {
  98653. cx = p2x - d4x; cy = p2y - d4y; cz = p2z - d4z;
  98654. nx = -a4x; ny = -a4y; nz = -a4z;
  98655. }
  98656. s1x = d5x; s1y = d5y; s1z = d5z;
  98657. n1x = -a5x; n1y = -a5y; n1z = -a5z;
  98658. s2x = d6x; s2y = d6y; s2z = d6z;
  98659. n2x = -a6x; n2y = -a6y; n2z = -a6z;
  98660. }
  98661. else if (minIndex == 4) {// b2.y * b1
  98662. swap = true;
  98663. if (!right) {
  98664. cx = p2x + d5x; cy = p2y + d5y; cz = p2z + d5z;
  98665. nx = a5x; ny = a5y; nz = a5z;
  98666. } else {
  98667. cx = p2x - d5x; cy = p2y - d5y; cz = p2z - d5z;
  98668. nx = -a5x; ny = -a5y; nz = -a5z;
  98669. }
  98670. s1x = d4x; s1y = d4y; s1z = d4z;
  98671. n1x = -a4x; n1y = -a4y; n1z = -a4z;
  98672. s2x = d6x; s2y = d6y; s2z = d6z;
  98673. n2x = -a6x; n2y = -a6y; n2z = -a6z;
  98674. }
  98675. else if (minIndex == 5) {// b2.z * b1
  98676. swap = true;
  98677. if (!right) {
  98678. cx = p2x + d6x; cy = p2y + d6y; cz = p2z + d6z;
  98679. nx = a6x; ny = a6y; nz = a6z;
  98680. } else {
  98681. cx = p2x - d6x; cy = p2y - d6y; cz = p2z - d6z;
  98682. nx = -a6x; ny = -a6y; nz = -a6z;
  98683. }
  98684. s1x = d4x; s1y = d4y; s1z = d4z;
  98685. n1x = -a4x; n1y = -a4y; n1z = -a4z;
  98686. s2x = d5x; s2y = d5y; s2z = d5z;
  98687. n2x = -a5x; n2y = -a5y; n2z = -a5z;
  98688. }
  98689. else if (minIndex == 6) {// b1.x * b2.x
  98690. nx = a7x; ny = a7y; nz = a7z;
  98691. n1x = a1x; n1y = a1y; n1z = a1z;
  98692. n2x = a4x; n2y = a4y; n2z = a4z;
  98693. }
  98694. else if (minIndex == 7) {// b1.x * b2.y
  98695. nx = a8x; ny = a8y; nz = a8z;
  98696. n1x = a1x; n1y = a1y; n1z = a1z;
  98697. n2x = a5x; n2y = a5y; n2z = a5z;
  98698. }
  98699. else if (minIndex == 8) {// b1.x * b2.z
  98700. nx = a9x; ny = a9y; nz = a9z;
  98701. n1x = a1x; n1y = a1y; n1z = a1z;
  98702. n2x = a6x; n2y = a6y; n2z = a6z;
  98703. }
  98704. else if (minIndex == 9) {// b1.y * b2.x
  98705. nx = aax; ny = aay; nz = aaz;
  98706. n1x = a2x; n1y = a2y; n1z = a2z;
  98707. n2x = a4x; n2y = a4y; n2z = a4z
  98708. }
  98709. else if (minIndex == 10) {// b1.y * b2.y
  98710. nx = abx; ny = aby; nz = abz;
  98711. n1x = a2x; n1y = a2y; n1z = a2z;
  98712. n2x = a5x; n2y = a5y; n2z = a5z;
  98713. }
  98714. else if (minIndex == 11) {// b1.y * b2.z
  98715. nx = acx; ny = acy; nz = acz;
  98716. n1x = a2x; n1y = a2y; n1z = a2z;
  98717. n2x = a6x; n2y = a6y; n2z = a6z;
  98718. }
  98719. else if (minIndex == 12) {// b1.z * b2.x
  98720. nx = adx; ny = ady; nz = adz;
  98721. n1x = a3x; n1y = a3y; n1z = a3z;
  98722. n2x = a4x; n2y = a4y; n2z = a4z;
  98723. }
  98724. else if (minIndex == 13) {// b1.z * b2.y
  98725. nx = aex; ny = aey; nz = aez;
  98726. n1x = a3x; n1y = a3y; n1z = a3z;
  98727. n2x = a5x; n2y = a5y; n2z = a5z;
  98728. }
  98729. else if (minIndex == 14) {// b1.z * b2.z
  98730. nx = afx; ny = afy; nz = afz;
  98731. n1x = a3x; n1y = a3y; n1z = a3z;
  98732. n2x = a6x; n2y = a6y; n2z = a6z;
  98733. }
  98734. //__________________________________________
  98735. var v;
  98736. if (minIndex > 5) {
  98737. if (!right) {
  98738. nx = -nx; ny = -ny; nz = -nz;
  98739. }
  98740. var distance;
  98741. var maxDistance;
  98742. var vx;
  98743. var vy;
  98744. var vz;
  98745. var v1x;
  98746. var v1y;
  98747. var v1z;
  98748. var v2x;
  98749. var v2y;
  98750. var v2z;
  98751. //vertex1;
  98752. v1x = V1[0]; v1y = V1[1]; v1z = V1[2];
  98753. maxDistance = nx * v1x + ny * v1y + nz * v1z;
  98754. //vertex2;
  98755. vx = V1[3]; vy = V1[4]; vz = V1[5];
  98756. distance = nx * vx + ny * vy + nz * vz;
  98757. if (distance > maxDistance) {
  98758. maxDistance = distance;
  98759. v1x = vx; v1y = vy; v1z = vz;
  98760. }
  98761. //vertex3;
  98762. vx = V1[6]; vy = V1[7]; vz = V1[8];
  98763. distance = nx * vx + ny * vy + nz * vz;
  98764. if (distance > maxDistance) {
  98765. maxDistance = distance;
  98766. v1x = vx; v1y = vy; v1z = vz;
  98767. }
  98768. //vertex4;
  98769. vx = V1[9]; vy = V1[10]; vz = V1[11];
  98770. distance = nx * vx + ny * vy + nz * vz;
  98771. if (distance > maxDistance) {
  98772. maxDistance = distance;
  98773. v1x = vx; v1y = vy; v1z = vz;
  98774. }
  98775. //vertex5;
  98776. vx = V1[12]; vy = V1[13]; vz = V1[14];
  98777. distance = nx * vx + ny * vy + nz * vz;
  98778. if (distance > maxDistance) {
  98779. maxDistance = distance;
  98780. v1x = vx; v1y = vy; v1z = vz;
  98781. }
  98782. //vertex6;
  98783. vx = V1[15]; vy = V1[16]; vz = V1[17];
  98784. distance = nx * vx + ny * vy + nz * vz;
  98785. if (distance > maxDistance) {
  98786. maxDistance = distance;
  98787. v1x = vx; v1y = vy; v1z = vz;
  98788. }
  98789. //vertex7;
  98790. vx = V1[18]; vy = V1[19]; vz = V1[20];
  98791. distance = nx * vx + ny * vy + nz * vz;
  98792. if (distance > maxDistance) {
  98793. maxDistance = distance;
  98794. v1x = vx; v1y = vy; v1z = vz;
  98795. }
  98796. //vertex8;
  98797. vx = V1[21]; vy = V1[22]; vz = V1[23];
  98798. distance = nx * vx + ny * vy + nz * vz;
  98799. if (distance > maxDistance) {
  98800. maxDistance = distance;
  98801. v1x = vx; v1y = vy; v1z = vz;
  98802. }
  98803. //vertex1;
  98804. v2x = V2[0]; v2y = V2[1]; v2z = V2[2];
  98805. maxDistance = nx * v2x + ny * v2y + nz * v2z;
  98806. //vertex2;
  98807. vx = V2[3]; vy = V2[4]; vz = V2[5];
  98808. distance = nx * vx + ny * vy + nz * vz;
  98809. if (distance < maxDistance) {
  98810. maxDistance = distance;
  98811. v2x = vx; v2y = vy; v2z = vz;
  98812. }
  98813. //vertex3;
  98814. vx = V2[6]; vy = V2[7]; vz = V2[8];
  98815. distance = nx * vx + ny * vy + nz * vz;
  98816. if (distance < maxDistance) {
  98817. maxDistance = distance;
  98818. v2x = vx; v2y = vy; v2z = vz;
  98819. }
  98820. //vertex4;
  98821. vx = V2[9]; vy = V2[10]; vz = V2[11];
  98822. distance = nx * vx + ny * vy + nz * vz;
  98823. if (distance < maxDistance) {
  98824. maxDistance = distance;
  98825. v2x = vx; v2y = vy; v2z = vz;
  98826. }
  98827. //vertex5;
  98828. vx = V2[12]; vy = V2[13]; vz = V2[14];
  98829. distance = nx * vx + ny * vy + nz * vz;
  98830. if (distance < maxDistance) {
  98831. maxDistance = distance;
  98832. v2x = vx; v2y = vy; v2z = vz;
  98833. }
  98834. //vertex6;
  98835. vx = V2[15]; vy = V2[16]; vz = V2[17];
  98836. distance = nx * vx + ny * vy + nz * vz;
  98837. if (distance < maxDistance) {
  98838. maxDistance = distance;
  98839. v2x = vx; v2y = vy; v2z = vz;
  98840. }
  98841. //vertex7;
  98842. vx = V2[18]; vy = V2[19]; vz = V2[20];
  98843. distance = nx * vx + ny * vy + nz * vz;
  98844. if (distance < maxDistance) {
  98845. maxDistance = distance;
  98846. v2x = vx; v2y = vy; v2z = vz;
  98847. }
  98848. //vertex8;
  98849. vx = V2[21]; vy = V2[22]; vz = V2[23];
  98850. distance = nx * vx + ny * vy + nz * vz;
  98851. if (distance < maxDistance) {
  98852. maxDistance = distance;
  98853. v2x = vx; v2y = vy; v2z = vz;
  98854. }
  98855. vx = v2x - v1x; vy = v2y - v1y; vz = v2z - v1z;
  98856. dot1 = n1x * n2x + n1y * n2y + n1z * n2z;
  98857. var t = (vx * (n1x - n2x * dot1) + vy * (n1y - n2y * dot1) + vz * (n1z - n2z * dot1)) / (1 - dot1 * dot1);
  98858. 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);
  98859. return;
  98860. }
  98861. // now detect face-face collision...
  98862. // target quad
  98863. var q1x;
  98864. var q1y;
  98865. var q1z;
  98866. var q2x;
  98867. var q2y;
  98868. var q2z;
  98869. var q3x;
  98870. var q3y;
  98871. var q3z;
  98872. var q4x;
  98873. var q4y;
  98874. var q4z;
  98875. // search support face and vertex
  98876. var minDot = 1;
  98877. var dot = 0;
  98878. var minDotIndex = 0;
  98879. if (swap) {
  98880. dot = a1x * nx + a1y * ny + a1z * nz;
  98881. if (dot < minDot) {
  98882. minDot = dot;
  98883. minDotIndex = 0;
  98884. }
  98885. if (-dot < minDot) {
  98886. minDot = -dot;
  98887. minDotIndex = 1;
  98888. }
  98889. dot = a2x * nx + a2y * ny + a2z * nz;
  98890. if (dot < minDot) {
  98891. minDot = dot;
  98892. minDotIndex = 2;
  98893. }
  98894. if (-dot < minDot) {
  98895. minDot = -dot;
  98896. minDotIndex = 3;
  98897. }
  98898. dot = a3x * nx + a3y * ny + a3z * nz;
  98899. if (dot < minDot) {
  98900. minDot = dot;
  98901. minDotIndex = 4;
  98902. }
  98903. if (-dot < minDot) {
  98904. minDot = -dot;
  98905. minDotIndex = 5;
  98906. }
  98907. if (minDotIndex == 0) {// x+ face
  98908. q1x = V1[0]; q1y = V1[1]; q1z = V1[2];//vertex1
  98909. q2x = V1[6]; q2y = V1[7]; q2z = V1[8];//vertex3
  98910. q3x = V1[9]; q3y = V1[10]; q3z = V1[11];//vertex4
  98911. q4x = V1[3]; q4y = V1[4]; q4z = V1[5];//vertex2
  98912. }
  98913. else if (minDotIndex == 1) {// x- face
  98914. q1x = V1[15]; q1y = V1[16]; q1z = V1[17];//vertex6
  98915. q2x = V1[21]; q2y = V1[22]; q2z = V1[23];//vertex8
  98916. q3x = V1[18]; q3y = V1[19]; q3z = V1[20];//vertex7
  98917. q4x = V1[12]; q4y = V1[13]; q4z = V1[14];//vertex5
  98918. }
  98919. else if (minDotIndex == 2) {// y+ face
  98920. q1x = V1[12]; q1y = V1[13]; q1z = V1[14];//vertex5
  98921. q2x = V1[0]; q2y = V1[1]; q2z = V1[2];//vertex1
  98922. q3x = V1[3]; q3y = V1[4]; q3z = V1[5];//vertex2
  98923. q4x = V1[15]; q4y = V1[16]; q4z = V1[17];//vertex6
  98924. }
  98925. else if (minDotIndex == 3) {// y- face
  98926. q1x = V1[21]; q1y = V1[22]; q1z = V1[23];//vertex8
  98927. q2x = V1[9]; q2y = V1[10]; q2z = V1[11];//vertex4
  98928. q3x = V1[6]; q3y = V1[7]; q3z = V1[8];//vertex3
  98929. q4x = V1[18]; q4y = V1[19]; q4z = V1[20];//vertex7
  98930. }
  98931. else if (minDotIndex == 4) {// z+ face
  98932. q1x = V1[12]; q1y = V1[13]; q1z = V1[14];//vertex5
  98933. q2x = V1[18]; q2y = V1[19]; q2z = V1[20];//vertex7
  98934. q3x = V1[6]; q3y = V1[7]; q3z = V1[8];//vertex3
  98935. q4x = V1[0]; q4y = V1[1]; q4z = V1[2];//vertex1
  98936. }
  98937. else if (minDotIndex == 5) {// z- face
  98938. q1x = V1[3]; q1y = V1[4]; q1z = V1[5];//vertex2
  98939. q2x = V1[6]; q2y = V1[7]; q2z = V1[8];//vertex4
  98940. q3x = V1[21]; q3y = V1[22]; q3z = V1[23];//vertex8
  98941. q4x = V1[15]; q4y = V1[16]; q4z = V1[17];//vertex6
  98942. }
  98943. } else {
  98944. dot = a4x * nx + a4y * ny + a4z * nz;
  98945. if (dot < minDot) {
  98946. minDot = dot;
  98947. minDotIndex = 0;
  98948. }
  98949. if (-dot < minDot) {
  98950. minDot = -dot;
  98951. minDotIndex = 1;
  98952. }
  98953. dot = a5x * nx + a5y * ny + a5z * nz;
  98954. if (dot < minDot) {
  98955. minDot = dot;
  98956. minDotIndex = 2;
  98957. }
  98958. if (-dot < minDot) {
  98959. minDot = -dot;
  98960. minDotIndex = 3;
  98961. }
  98962. dot = a6x * nx + a6y * ny + a6z * nz;
  98963. if (dot < minDot) {
  98964. minDot = dot;
  98965. minDotIndex = 4;
  98966. }
  98967. if (-dot < minDot) {
  98968. minDot = -dot;
  98969. minDotIndex = 5;
  98970. }
  98971. //______________________________________________________
  98972. if (minDotIndex == 0) {// x+ face
  98973. q1x = V2[0]; q1y = V2[1]; q1z = V2[2];//vertex1
  98974. q2x = V2[6]; q2y = V2[7]; q2z = V2[8];//vertex3
  98975. q3x = V2[9]; q3y = V2[10]; q3z = V2[11];//vertex4
  98976. q4x = V2[3]; q4y = V2[4]; q4z = V2[5];//vertex2
  98977. }
  98978. else if (minDotIndex == 1) {// x- face
  98979. q1x = V2[15]; q1y = V2[16]; q1z = V2[17];//vertex6
  98980. q2x = V2[21]; q2y = V2[22]; q2z = V2[23]; //vertex8
  98981. q3x = V2[18]; q3y = V2[19]; q3z = V2[20];//vertex7
  98982. q4x = V2[12]; q4y = V2[13]; q4z = V2[14];//vertex5
  98983. }
  98984. else if (minDotIndex == 2) {// y+ face
  98985. q1x = V2[12]; q1y = V2[13]; q1z = V2[14];//vertex5
  98986. q2x = V2[0]; q2y = V2[1]; q2z = V2[2];//vertex1
  98987. q3x = V2[3]; q3y = V2[4]; q3z = V2[5];//vertex2
  98988. q4x = V2[15]; q4y = V2[16]; q4z = V2[17];//vertex6
  98989. }
  98990. else if (minDotIndex == 3) {// y- face
  98991. q1x = V2[21]; q1y = V2[22]; q1z = V2[23];//vertex8
  98992. q2x = V2[9]; q2y = V2[10]; q2z = V2[11];//vertex4
  98993. q3x = V2[6]; q3y = V2[7]; q3z = V2[8];//vertex3
  98994. q4x = V2[18]; q4y = V2[19]; q4z = V2[20];//vertex7
  98995. }
  98996. else if (minDotIndex == 4) {// z+ face
  98997. q1x = V2[12]; q1y = V2[13]; q1z = V2[14];//vertex5
  98998. q2x = V2[18]; q2y = V2[19]; q2z = V2[20];//vertex7
  98999. q3x = V2[6]; q3y = V2[7]; q3z = V2[8];//vertex3
  99000. q4x = V2[0]; q4y = V2[1]; q4z = V2[2];//vertex1
  99001. }
  99002. else if (minDotIndex == 5) {// z- face
  99003. q1x = V2[3]; q1y = V2[4]; q1z = V2[5];//vertex2
  99004. q2x = V2[9]; q2y = V2[10]; q2z = V2[11];//vertex4
  99005. q3x = V2[21]; q3y = V2[22]; q3z = V2[23];//vertex8
  99006. q4x = V2[15]; q4y = V2[16]; q4z = V2[17];//vertex6
  99007. }
  99008. }
  99009. // clip vertices
  99010. var numClipVertices;
  99011. var numAddedClipVertices;
  99012. var index;
  99013. var x1;
  99014. var y1;
  99015. var z1;
  99016. var x2;
  99017. var y2;
  99018. var z2;
  99019. this.clipVertices1[0] = q1x;
  99020. this.clipVertices1[1] = q1y;
  99021. this.clipVertices1[2] = q1z;
  99022. this.clipVertices1[3] = q2x;
  99023. this.clipVertices1[4] = q2y;
  99024. this.clipVertices1[5] = q2z;
  99025. this.clipVertices1[6] = q3x;
  99026. this.clipVertices1[7] = q3y;
  99027. this.clipVertices1[8] = q3z;
  99028. this.clipVertices1[9] = q4x;
  99029. this.clipVertices1[10] = q4y;
  99030. this.clipVertices1[11] = q4z;
  99031. numAddedClipVertices = 0;
  99032. x1 = this.clipVertices1[9];
  99033. y1 = this.clipVertices1[10];
  99034. z1 = this.clipVertices1[11];
  99035. dot1 = (x1 - cx - s1x) * n1x + (y1 - cy - s1y) * n1y + (z1 - cz - s1z) * n1z;
  99036. //var i = 4;
  99037. //while(i--){
  99038. for (var i = 0; i < 4; i++) {
  99039. index = i * 3;
  99040. x2 = this.clipVertices1[index];
  99041. y2 = this.clipVertices1[index + 1];
  99042. z2 = this.clipVertices1[index + 2];
  99043. dot2 = (x2 - cx - s1x) * n1x + (y2 - cy - s1y) * n1y + (z2 - cz - s1z) * n1z;
  99044. if (dot1 > 0) {
  99045. if (dot2 > 0) {
  99046. index = numAddedClipVertices * 3;
  99047. numAddedClipVertices++;
  99048. this.clipVertices2[index] = x2;
  99049. this.clipVertices2[index + 1] = y2;
  99050. this.clipVertices2[index + 2] = z2;
  99051. } else {
  99052. index = numAddedClipVertices * 3;
  99053. numAddedClipVertices++;
  99054. t = dot1 / (dot1 - dot2);
  99055. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  99056. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  99057. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  99058. }
  99059. } else {
  99060. if (dot2 > 0) {
  99061. index = numAddedClipVertices * 3;
  99062. numAddedClipVertices++;
  99063. t = dot1 / (dot1 - dot2);
  99064. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  99065. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  99066. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  99067. index = numAddedClipVertices * 3;
  99068. numAddedClipVertices++;
  99069. this.clipVertices2[index] = x2;
  99070. this.clipVertices2[index + 1] = y2;
  99071. this.clipVertices2[index + 2] = z2;
  99072. }
  99073. }
  99074. x1 = x2;
  99075. y1 = y2;
  99076. z1 = z2;
  99077. dot1 = dot2;
  99078. }
  99079. numClipVertices = numAddedClipVertices;
  99080. if (numClipVertices == 0) return;
  99081. numAddedClipVertices = 0;
  99082. index = (numClipVertices - 1) * 3;
  99083. x1 = this.clipVertices2[index];
  99084. y1 = this.clipVertices2[index + 1];
  99085. z1 = this.clipVertices2[index + 2];
  99086. dot1 = (x1 - cx - s2x) * n2x + (y1 - cy - s2y) * n2y + (z1 - cz - s2z) * n2z;
  99087. //i = numClipVertices;
  99088. //while(i--){
  99089. for (i = 0; i < numClipVertices; i++) {
  99090. index = i * 3;
  99091. x2 = this.clipVertices2[index];
  99092. y2 = this.clipVertices2[index + 1];
  99093. z2 = this.clipVertices2[index + 2];
  99094. dot2 = (x2 - cx - s2x) * n2x + (y2 - cy - s2y) * n2y + (z2 - cz - s2z) * n2z;
  99095. if (dot1 > 0) {
  99096. if (dot2 > 0) {
  99097. index = numAddedClipVertices * 3;
  99098. numAddedClipVertices++;
  99099. this.clipVertices1[index] = x2;
  99100. this.clipVertices1[index + 1] = y2;
  99101. this.clipVertices1[index + 2] = z2;
  99102. } else {
  99103. index = numAddedClipVertices * 3;
  99104. numAddedClipVertices++;
  99105. t = dot1 / (dot1 - dot2);
  99106. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  99107. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  99108. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  99109. }
  99110. } else {
  99111. if (dot2 > 0) {
  99112. index = numAddedClipVertices * 3;
  99113. numAddedClipVertices++;
  99114. t = dot1 / (dot1 - dot2);
  99115. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  99116. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  99117. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  99118. index = numAddedClipVertices * 3;
  99119. numAddedClipVertices++;
  99120. this.clipVertices1[index] = x2;
  99121. this.clipVertices1[index + 1] = y2;
  99122. this.clipVertices1[index + 2] = z2;
  99123. }
  99124. }
  99125. x1 = x2;
  99126. y1 = y2;
  99127. z1 = z2;
  99128. dot1 = dot2;
  99129. }
  99130. numClipVertices = numAddedClipVertices;
  99131. if (numClipVertices == 0) return;
  99132. numAddedClipVertices = 0;
  99133. index = (numClipVertices - 1) * 3;
  99134. x1 = this.clipVertices1[index];
  99135. y1 = this.clipVertices1[index + 1];
  99136. z1 = this.clipVertices1[index + 2];
  99137. dot1 = (x1 - cx + s1x) * -n1x + (y1 - cy + s1y) * -n1y + (z1 - cz + s1z) * -n1z;
  99138. //i = numClipVertices;
  99139. //while(i--){
  99140. for (i = 0; i < numClipVertices; i++) {
  99141. index = i * 3;
  99142. x2 = this.clipVertices1[index];
  99143. y2 = this.clipVertices1[index + 1];
  99144. z2 = this.clipVertices1[index + 2];
  99145. dot2 = (x2 - cx + s1x) * -n1x + (y2 - cy + s1y) * -n1y + (z2 - cz + s1z) * -n1z;
  99146. if (dot1 > 0) {
  99147. if (dot2 > 0) {
  99148. index = numAddedClipVertices * 3;
  99149. numAddedClipVertices++;
  99150. this.clipVertices2[index] = x2;
  99151. this.clipVertices2[index + 1] = y2;
  99152. this.clipVertices2[index + 2] = z2;
  99153. } else {
  99154. index = numAddedClipVertices * 3;
  99155. numAddedClipVertices++;
  99156. t = dot1 / (dot1 - dot2);
  99157. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  99158. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  99159. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  99160. }
  99161. } else {
  99162. if (dot2 > 0) {
  99163. index = numAddedClipVertices * 3;
  99164. numAddedClipVertices++;
  99165. t = dot1 / (dot1 - dot2);
  99166. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  99167. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  99168. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  99169. index = numAddedClipVertices * 3;
  99170. numAddedClipVertices++;
  99171. this.clipVertices2[index] = x2;
  99172. this.clipVertices2[index + 1] = y2;
  99173. this.clipVertices2[index + 2] = z2;
  99174. }
  99175. }
  99176. x1 = x2;
  99177. y1 = y2;
  99178. z1 = z2;
  99179. dot1 = dot2;
  99180. }
  99181. numClipVertices = numAddedClipVertices;
  99182. if (numClipVertices == 0) return;
  99183. numAddedClipVertices = 0;
  99184. index = (numClipVertices - 1) * 3;
  99185. x1 = this.clipVertices2[index];
  99186. y1 = this.clipVertices2[index + 1];
  99187. z1 = this.clipVertices2[index + 2];
  99188. dot1 = (x1 - cx + s2x) * -n2x + (y1 - cy + s2y) * -n2y + (z1 - cz + s2z) * -n2z;
  99189. //i = numClipVertices;
  99190. //while(i--){
  99191. for (i = 0; i < numClipVertices; i++) {
  99192. index = i * 3;
  99193. x2 = this.clipVertices2[index];
  99194. y2 = this.clipVertices2[index + 1];
  99195. z2 = this.clipVertices2[index + 2];
  99196. dot2 = (x2 - cx + s2x) * -n2x + (y2 - cy + s2y) * -n2y + (z2 - cz + s2z) * -n2z;
  99197. if (dot1 > 0) {
  99198. if (dot2 > 0) {
  99199. index = numAddedClipVertices * 3;
  99200. numAddedClipVertices++;
  99201. this.clipVertices1[index] = x2;
  99202. this.clipVertices1[index + 1] = y2;
  99203. this.clipVertices1[index + 2] = z2;
  99204. } else {
  99205. index = numAddedClipVertices * 3;
  99206. numAddedClipVertices++;
  99207. t = dot1 / (dot1 - dot2);
  99208. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  99209. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  99210. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  99211. }
  99212. } else {
  99213. if (dot2 > 0) {
  99214. index = numAddedClipVertices * 3;
  99215. numAddedClipVertices++;
  99216. t = dot1 / (dot1 - dot2);
  99217. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  99218. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  99219. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  99220. index = numAddedClipVertices * 3;
  99221. numAddedClipVertices++;
  99222. this.clipVertices1[index] = x2;
  99223. this.clipVertices1[index + 1] = y2;
  99224. this.clipVertices1[index + 2] = z2;
  99225. }
  99226. }
  99227. x1 = x2;
  99228. y1 = y2;
  99229. z1 = z2;
  99230. dot1 = dot2;
  99231. }
  99232. numClipVertices = numAddedClipVertices;
  99233. if (swap) {
  99234. var tb = b1;
  99235. b1 = b2;
  99236. b2 = tb;
  99237. }
  99238. if (numClipVertices == 0) return;
  99239. var flipped = b1 != shape1;
  99240. if (numClipVertices > 4) {
  99241. x1 = (q1x + q2x + q3x + q4x) * 0.25;
  99242. y1 = (q1y + q2y + q3y + q4y) * 0.25;
  99243. z1 = (q1z + q2z + q3z + q4z) * 0.25;
  99244. n1x = q1x - x1;
  99245. n1y = q1y - y1;
  99246. n1z = q1z - z1;
  99247. n2x = q2x - x1;
  99248. n2y = q2y - y1;
  99249. n2z = q2z - z1;
  99250. var index1 = 0;
  99251. var index2 = 0;
  99252. var index3 = 0;
  99253. var index4 = 0;
  99254. var maxDot = -this.INF;
  99255. minDot = this.INF;
  99256. //i = numClipVertices;
  99257. //while(i--){
  99258. for (i = 0; i < numClipVertices; i++) {
  99259. this.used[i] = false;
  99260. index = i * 3;
  99261. x1 = this.clipVertices1[index];
  99262. y1 = this.clipVertices1[index + 1];
  99263. z1 = this.clipVertices1[index + 2];
  99264. dot = x1 * n1x + y1 * n1y + z1 * n1z;
  99265. if (dot < minDot) {
  99266. minDot = dot;
  99267. index1 = i;
  99268. }
  99269. if (dot > maxDot) {
  99270. maxDot = dot;
  99271. index3 = i;
  99272. }
  99273. }
  99274. this.used[index1] = true;
  99275. this.used[index3] = true;
  99276. maxDot = -this.INF;
  99277. minDot = this.INF;
  99278. //i = numClipVertices;
  99279. //while(i--){
  99280. for (i = 0; i < numClipVertices; i++) {
  99281. if (this.used[i]) continue;
  99282. index = i * 3;
  99283. x1 = this.clipVertices1[index];
  99284. y1 = this.clipVertices1[index + 1];
  99285. z1 = this.clipVertices1[index + 2];
  99286. dot = x1 * n2x + y1 * n2y + z1 * n2z;
  99287. if (dot < minDot) {
  99288. minDot = dot;
  99289. index2 = i;
  99290. }
  99291. if (dot > maxDot) {
  99292. maxDot = dot;
  99293. index4 = i;
  99294. }
  99295. }
  99296. index = index1 * 3;
  99297. x1 = this.clipVertices1[index];
  99298. y1 = this.clipVertices1[index + 1];
  99299. z1 = this.clipVertices1[index + 2];
  99300. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  99301. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  99302. index = index2 * 3;
  99303. x1 = this.clipVertices1[index];
  99304. y1 = this.clipVertices1[index + 1];
  99305. z1 = this.clipVertices1[index + 2];
  99306. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  99307. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  99308. index = index3 * 3;
  99309. x1 = this.clipVertices1[index];
  99310. y1 = this.clipVertices1[index + 1];
  99311. z1 = this.clipVertices1[index + 2];
  99312. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  99313. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  99314. index = index4 * 3;
  99315. x1 = this.clipVertices1[index];
  99316. y1 = this.clipVertices1[index + 1];
  99317. z1 = this.clipVertices1[index + 2];
  99318. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  99319. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  99320. } else {
  99321. //i = numClipVertices;
  99322. //while(i--){
  99323. for (i = 0; i < numClipVertices; i++) {
  99324. index = i * 3;
  99325. x1 = this.clipVertices1[index];
  99326. y1 = this.clipVertices1[index + 1];
  99327. z1 = this.clipVertices1[index + 2];
  99328. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  99329. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  99330. }
  99331. }
  99332. };
  99333. /**
  99334. * A collision detector which detects collisions between sphere and box.
  99335. * @author saharan
  99336. */
  99337. OIMO.SphereBoxCollisionDetector = function (flip) {
  99338. OIMO.CollisionDetector.call(this);
  99339. this.flip = flip;
  99340. };
  99341. OIMO.SphereBoxCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  99342. OIMO.SphereBoxCollisionDetector.prototype.constructor = OIMO.SphereBoxCollisionDetector;
  99343. OIMO.SphereBoxCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  99344. var s;
  99345. var b;
  99346. if (this.flip) {
  99347. s = (shape2);
  99348. b = (shape1);
  99349. } else {
  99350. s = (shape1);
  99351. b = (shape2);
  99352. }
  99353. var D = b.dimentions;
  99354. var ps = s.position;
  99355. var psx = ps.x;
  99356. var psy = ps.y;
  99357. var psz = ps.z;
  99358. var pb = b.position;
  99359. var pbx = pb.x;
  99360. var pby = pb.y;
  99361. var pbz = pb.z;
  99362. var rad = s.radius;
  99363. var hw = b.halfWidth;
  99364. var hh = b.halfHeight;
  99365. var hd = b.halfDepth;
  99366. var dx = psx - pbx;
  99367. var dy = psy - pby;
  99368. var dz = psz - pbz;
  99369. var sx = D[0] * dx + D[1] * dy + D[2] * dz;
  99370. var sy = D[3] * dx + D[4] * dy + D[5] * dz;
  99371. var sz = D[6] * dx + D[7] * dy + D[8] * dz;
  99372. var cx;
  99373. var cy;
  99374. var cz;
  99375. var len;
  99376. var invLen;
  99377. var overlap = 0;
  99378. if (sx > hw) {
  99379. sx = hw;
  99380. } else if (sx < -hw) {
  99381. sx = -hw;
  99382. } else {
  99383. overlap = 1;
  99384. }
  99385. if (sy > hh) {
  99386. sy = hh;
  99387. } else if (sy < -hh) {
  99388. sy = -hh;
  99389. } else {
  99390. overlap |= 2;
  99391. }
  99392. if (sz > hd) {
  99393. sz = hd;
  99394. } else if (sz < -hd) {
  99395. sz = -hd;
  99396. } else {
  99397. overlap |= 4;
  99398. }
  99399. if (overlap == 7) {
  99400. // center of sphere is in the box
  99401. if (sx < 0) {
  99402. dx = hw + sx;
  99403. } else {
  99404. dx = hw - sx;
  99405. }
  99406. if (sy < 0) {
  99407. dy = hh + sy;
  99408. } else {
  99409. dy = hh - sy;
  99410. }
  99411. if (sz < 0) {
  99412. dz = hd + sz;
  99413. } else {
  99414. dz = hd - sz;
  99415. }
  99416. if (dx < dy) {
  99417. if (dx < dz) {
  99418. len = dx - hw;
  99419. if (sx < 0) {
  99420. sx = -hw;
  99421. dx = D[0];
  99422. dy = D[1];
  99423. dz = D[2];
  99424. } else {
  99425. sx = hw;
  99426. dx = -D[0];
  99427. dy = -D[1];
  99428. dz = -D[2];
  99429. }
  99430. } else {
  99431. len = dz - hd;
  99432. if (sz < 0) {
  99433. sz = -hd;
  99434. dx = D[6];
  99435. dy = D[7];
  99436. dz = D[8];
  99437. } else {
  99438. sz = hd;
  99439. dx = -D[6];
  99440. dy = -D[7];
  99441. dz = -D[8];
  99442. }
  99443. }
  99444. } else {
  99445. if (dy < dz) {
  99446. len = dy - hh;
  99447. if (sy < 0) {
  99448. sy = -hh;
  99449. dx = D[3];
  99450. dy = D[4];
  99451. dz = D[5];
  99452. } else {
  99453. sy = hh;
  99454. dx = -D[3];
  99455. dy = -D[4];
  99456. dz = -D[5];
  99457. }
  99458. } else {
  99459. len = dz - hd;
  99460. if (sz < 0) {
  99461. sz = -hd;
  99462. dx = D[6];
  99463. dy = D[7];
  99464. dz = D[8];
  99465. } else {
  99466. sz = hd;
  99467. dx = -D[6];
  99468. dy = -D[7];
  99469. dz = -D[8];
  99470. }
  99471. }
  99472. }
  99473. cx = pbx + sx * D[0] + sy * D[3] + sz * D[6];
  99474. cy = pby + sx * D[1] + sy * D[4] + sz * D[7];
  99475. cz = pbz + sx * D[2] + sy * D[5] + sz * D[8];
  99476. manifold.addPoint(psx + rad * dx, psy + rad * dy, psz + rad * dz, dx, dy, dz, len - rad, this.flip);
  99477. } else {
  99478. cx = pbx + sx * D[0] + sy * D[3] + sz * D[6];
  99479. cy = pby + sx * D[1] + sy * D[4] + sz * D[7];
  99480. cz = pbz + sx * D[2] + sy * D[5] + sz * D[8];
  99481. dx = cx - ps.x;
  99482. dy = cy - ps.y;
  99483. dz = cz - ps.z;
  99484. len = dx * dx + dy * dy + dz * dz;
  99485. if (len > 0 && len < rad * rad) {
  99486. len = OIMO.sqrt(len);
  99487. invLen = 1 / len;
  99488. dx *= invLen;
  99489. dy *= invLen;
  99490. dz *= invLen;
  99491. manifold.addPoint(psx + rad * dx, psy + rad * dy, psz + rad * dz, dx, dy, dz, len - rad, this.flip);
  99492. }
  99493. }
  99494. };
  99495. /**
  99496. * A collision detector which detects collisions between two spheres.
  99497. * @author saharan
  99498. */
  99499. OIMO.SphereSphereCollisionDetector = function () {
  99500. OIMO.CollisionDetector.call(this);
  99501. };
  99502. OIMO.SphereSphereCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  99503. OIMO.SphereSphereCollisionDetector.prototype.constructor = OIMO.SphereSphereCollisionDetector;
  99504. OIMO.SphereSphereCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  99505. var s1 = shape1;
  99506. var s2 = shape2;
  99507. var p1 = s1.position;
  99508. var p2 = s2.position;
  99509. var dx = p2.x - p1.x;
  99510. var dy = p2.y - p1.y;
  99511. var dz = p2.z - p1.z;
  99512. var len = dx * dx + dy * dy + dz * dz;
  99513. var r1 = s1.radius;
  99514. var r2 = s2.radius;
  99515. var rad = r1 + r2;
  99516. if (len > 0 && len < rad * rad) {
  99517. len = OIMO.sqrt(len);
  99518. var invLen = 1 / len;
  99519. dx *= invLen;
  99520. dy *= invLen;
  99521. dz *= invLen;
  99522. manifold.addPoint(p1.x + dx * r1, p1.y + dy * r1, p1.z + dz * r1, dx, dy, dz, len - rad, false);
  99523. }
  99524. };
  99525. OIMO.BoxCylinderCollisionDetector = function (flip) {
  99526. OIMO.CollisionDetector.call(this);
  99527. this.flip = flip;
  99528. };
  99529. OIMO.BoxCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  99530. OIMO.BoxCylinderCollisionDetector.prototype.constructor = OIMO.BoxCylinderCollisionDetector;
  99531. OIMO.BoxCylinderCollisionDetector.prototype.getSep = function (c1, c2, sep, pos, dep) {
  99532. var t1x;
  99533. var t1y;
  99534. var t1z;
  99535. var t2x;
  99536. var t2y;
  99537. var t2z;
  99538. var sup = new OIMO.Vec3();
  99539. var len;
  99540. var p1x;
  99541. var p1y;
  99542. var p1z;
  99543. var p2x;
  99544. var p2y;
  99545. var p2z;
  99546. var v01x = c1.position.x;
  99547. var v01y = c1.position.y;
  99548. var v01z = c1.position.z;
  99549. var v02x = c2.position.x;
  99550. var v02y = c2.position.y;
  99551. var v02z = c2.position.z;
  99552. var v0x = v02x - v01x;
  99553. var v0y = v02y - v01y;
  99554. var v0z = v02z - v01z;
  99555. if (v0x * v0x + v0y * v0y + v0z * v0z == 0) v0y = 0.001;
  99556. var nx = -v0x;
  99557. var ny = -v0y;
  99558. var nz = -v0z;
  99559. this.supportPointB(c1, -nx, -ny, -nz, sup);
  99560. var v11x = sup.x;
  99561. var v11y = sup.y;
  99562. var v11z = sup.z;
  99563. this.supportPointC(c2, nx, ny, nz, sup);
  99564. var v12x = sup.x;
  99565. var v12y = sup.y;
  99566. var v12z = sup.z;
  99567. var v1x = v12x - v11x;
  99568. var v1y = v12y - v11y;
  99569. var v1z = v12z - v11z;
  99570. if (v1x * nx + v1y * ny + v1z * nz <= 0) {
  99571. return false;
  99572. }
  99573. nx = v1y * v0z - v1z * v0y;
  99574. ny = v1z * v0x - v1x * v0z;
  99575. nz = v1x * v0y - v1y * v0x;
  99576. if (nx * nx + ny * ny + nz * nz == 0) {
  99577. sep.init(v1x - v0x, v1y - v0y, v1z - v0z);
  99578. sep.normalize(sep);
  99579. pos.init((v11x + v12x) * 0.5, (v11y + v12y) * 0.5, (v11z + v12z) * 0.5);
  99580. return true;
  99581. }
  99582. this.supportPointB(c1, -nx, -ny, -nz, sup);
  99583. var v21x = sup.x;
  99584. var v21y = sup.y;
  99585. var v21z = sup.z;
  99586. this.supportPointC(c2, nx, ny, nz, sup);
  99587. var v22x = sup.x;
  99588. var v22y = sup.y;
  99589. var v22z = sup.z;
  99590. var v2x = v22x - v21x;
  99591. var v2y = v22y - v21y;
  99592. var v2z = v22z - v21z;
  99593. if (v2x * nx + v2y * ny + v2z * nz <= 0) {
  99594. return false;
  99595. }
  99596. t1x = v1x - v0x;
  99597. t1y = v1y - v0y;
  99598. t1z = v1z - v0z;
  99599. t2x = v2x - v0x;
  99600. t2y = v2y - v0y;
  99601. t2z = v2z - v0z;
  99602. nx = t1y * t2z - t1z * t2y;
  99603. ny = t1z * t2x - t1x * t2z;
  99604. nz = t1x * t2y - t1y * t2x;
  99605. if (nx * v0x + ny * v0y + nz * v0z > 0) {
  99606. t1x = v1x;
  99607. t1y = v1y;
  99608. t1z = v1z;
  99609. v1x = v2x;
  99610. v1y = v2y;
  99611. v1z = v2z;
  99612. v2x = t1x;
  99613. v2y = t1y;
  99614. v2z = t1z;
  99615. t1x = v11x;
  99616. t1y = v11y;
  99617. t1z = v11z;
  99618. v11x = v21x;
  99619. v11y = v21y;
  99620. v11z = v21z;
  99621. v21x = t1x;
  99622. v21y = t1y;
  99623. v21z = t1z;
  99624. t1x = v12x;
  99625. t1y = v12y;
  99626. t1z = v12z;
  99627. v12x = v22x;
  99628. v12y = v22y;
  99629. v12z = v22z;
  99630. v22x = t1x;
  99631. v22y = t1y;
  99632. v22z = t1z;
  99633. nx = -nx;
  99634. ny = -ny;
  99635. nz = -nz;
  99636. }
  99637. var iterations = 0;
  99638. while (true) {
  99639. if (++iterations > 100) {
  99640. return false;
  99641. }
  99642. this.supportPointB(c1, -nx, -ny, -nz, sup);
  99643. var v31x = sup.x;
  99644. var v31y = sup.y;
  99645. var v31z = sup.z;
  99646. this.supportPointC(c2, nx, ny, nz, sup);
  99647. var v32x = sup.x;
  99648. var v32y = sup.y;
  99649. var v32z = sup.z;
  99650. var v3x = v32x - v31x;
  99651. var v3y = v32y - v31y;
  99652. var v3z = v32z - v31z;
  99653. if (v3x * nx + v3y * ny + v3z * nz <= 0) {
  99654. return false;
  99655. }
  99656. if ((v1y * v3z - v1z * v3y) * v0x + (v1z * v3x - v1x * v3z) * v0y + (v1x * v3y - v1y * v3x) * v0z < 0) {
  99657. v2x = v3x;
  99658. v2y = v3y;
  99659. v2z = v3z;
  99660. v21x = v31x;
  99661. v21y = v31y;
  99662. v21z = v31z;
  99663. v22x = v32x;
  99664. v22y = v32y;
  99665. v22z = v32z;
  99666. t1x = v1x - v0x;
  99667. t1y = v1y - v0y;
  99668. t1z = v1z - v0z;
  99669. t2x = v3x - v0x;
  99670. t2y = v3y - v0y;
  99671. t2z = v3z - v0z;
  99672. nx = t1y * t2z - t1z * t2y;
  99673. ny = t1z * t2x - t1x * t2z;
  99674. nz = t1x * t2y - t1y * t2x;
  99675. continue;
  99676. }
  99677. if ((v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z < 0) {
  99678. v1x = v3x;
  99679. v1y = v3y;
  99680. v1z = v3z;
  99681. v11x = v31x;
  99682. v11y = v31y;
  99683. v11z = v31z;
  99684. v12x = v32x;
  99685. v12y = v32y;
  99686. v12z = v32z;
  99687. t1x = v3x - v0x;
  99688. t1y = v3y - v0y;
  99689. t1z = v3z - v0z;
  99690. t2x = v2x - v0x;
  99691. t2y = v2y - v0y;
  99692. t2z = v2z - v0z;
  99693. nx = t1y * t2z - t1z * t2y;
  99694. ny = t1z * t2x - t1x * t2z;
  99695. nz = t1x * t2y - t1y * t2x;
  99696. continue;
  99697. }
  99698. var hit = false;
  99699. while (true) {
  99700. t1x = v2x - v1x;
  99701. t1y = v2y - v1y;
  99702. t1z = v2z - v1z;
  99703. t2x = v3x - v1x;
  99704. t2y = v3y - v1y;
  99705. t2z = v3z - v1z;
  99706. nx = t1y * t2z - t1z * t2y;
  99707. ny = t1z * t2x - t1x * t2z;
  99708. nz = t1x * t2y - t1y * t2x;
  99709. len = 1 / OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  99710. nx *= len;
  99711. ny *= len;
  99712. nz *= len;
  99713. if (nx * v1x + ny * v1y + nz * v1z >= 0 && !hit) {
  99714. var b0 = (v1y * v2z - v1z * v2y) * v3x + (v1z * v2x - v1x * v2z) * v3y + (v1x * v2y - v1y * v2x) * v3z;
  99715. var b1 = (v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z;
  99716. var b2 = (v0y * v1z - v0z * v1y) * v3x + (v0z * v1x - v0x * v1z) * v3y + (v0x * v1y - v0y * v1x) * v3z;
  99717. var b3 = (v2y * v1z - v2z * v1y) * v0x + (v2z * v1x - v2x * v1z) * v0y + (v2x * v1y - v2y * v1x) * v0z;
  99718. var sum = b0 + b1 + b2 + b3;
  99719. if (sum <= 0) {
  99720. b0 = 0;
  99721. b1 = (v2y * v3z - v2z * v3y) * nx + (v2z * v3x - v2x * v3z) * ny + (v2x * v3y - v2y * v3x) * nz;
  99722. b2 = (v3y * v2z - v3z * v2y) * nx + (v3z * v2x - v3x * v2z) * ny + (v3x * v2y - v3y * v2x) * nz;
  99723. b3 = (v1y * v2z - v1z * v2y) * nx + (v1z * v2x - v1x * v2z) * ny + (v1x * v2y - v1y * v2x) * nz;
  99724. sum = b1 + b2 + b3;
  99725. }
  99726. var inv = 1 / sum;
  99727. p1x = (v01x * b0 + v11x * b1 + v21x * b2 + v31x * b3) * inv;
  99728. p1y = (v01y * b0 + v11y * b1 + v21y * b2 + v31y * b3) * inv;
  99729. p1z = (v01z * b0 + v11z * b1 + v21z * b2 + v31z * b3) * inv;
  99730. p2x = (v02x * b0 + v12x * b1 + v22x * b2 + v32x * b3) * inv;
  99731. p2y = (v02y * b0 + v12y * b1 + v22y * b2 + v32y * b3) * inv;
  99732. p2z = (v02z * b0 + v12z * b1 + v22z * b2 + v32z * b3) * inv;
  99733. hit = true;
  99734. }
  99735. this.supportPointB(c1, -nx, -ny, -nz, sup);
  99736. var v41x = sup.x;
  99737. var v41y = sup.y;
  99738. var v41z = sup.z;
  99739. this.supportPointC(c2, nx, ny, nz, sup);
  99740. var v42x = sup.x;
  99741. var v42y = sup.y;
  99742. var v42z = sup.z;
  99743. var v4x = v42x - v41x;
  99744. var v4y = v42y - v41y;
  99745. var v4z = v42z - v41z;
  99746. var separation = -(v4x * nx + v4y * ny + v4z * nz);
  99747. if ((v4x - v3x) * nx + (v4y - v3y) * ny + (v4z - v3z) * nz <= 0.01 || separation >= 0) {
  99748. if (hit) {
  99749. sep.init(-nx, -ny, -nz);
  99750. pos.init((p1x + p2x) * 0.5, (p1y + p2y) * 0.5, (p1z + p2z) * 0.5);
  99751. dep.x = separation;
  99752. return true;
  99753. }
  99754. return false;
  99755. }
  99756. if (
  99757. (v4y * v1z - v4z * v1y) * v0x +
  99758. (v4z * v1x - v4x * v1z) * v0y +
  99759. (v4x * v1y - v4y * v1x) * v0z < 0
  99760. ) {
  99761. if (
  99762. (v4y * v2z - v4z * v2y) * v0x +
  99763. (v4z * v2x - v4x * v2z) * v0y +
  99764. (v4x * v2y - v4y * v2x) * v0z < 0
  99765. ) {
  99766. v1x = v4x;
  99767. v1y = v4y;
  99768. v1z = v4z;
  99769. v11x = v41x;
  99770. v11y = v41y;
  99771. v11z = v41z;
  99772. v12x = v42x;
  99773. v12y = v42y;
  99774. v12z = v42z;
  99775. } else {
  99776. v3x = v4x;
  99777. v3y = v4y;
  99778. v3z = v4z;
  99779. v31x = v41x;
  99780. v31y = v41y;
  99781. v31z = v41z;
  99782. v32x = v42x;
  99783. v32y = v42y;
  99784. v32z = v42z;
  99785. }
  99786. } else {
  99787. if (
  99788. (v4y * v3z - v4z * v3y) * v0x +
  99789. (v4z * v3x - v4x * v3z) * v0y +
  99790. (v4x * v3y - v4y * v3x) * v0z < 0
  99791. ) {
  99792. v2x = v4x;
  99793. v2y = v4y;
  99794. v2z = v4z;
  99795. v21x = v41x;
  99796. v21y = v41y;
  99797. v21z = v41z;
  99798. v22x = v42x;
  99799. v22y = v42y;
  99800. v22z = v42z;
  99801. } else {
  99802. v1x = v4x;
  99803. v1y = v4y;
  99804. v1z = v4z;
  99805. v11x = v41x;
  99806. v11y = v41y;
  99807. v11z = v41z;
  99808. v12x = v42x;
  99809. v12y = v42y;
  99810. v12z = v42z;
  99811. }
  99812. }
  99813. }
  99814. }
  99815. //return false;
  99816. };
  99817. OIMO.BoxCylinderCollisionDetector.prototype.supportPointB = function (c, dx, dy, dz, out) {
  99818. var rot = c.rotation.elements;
  99819. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  99820. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  99821. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  99822. var w = c.halfWidth;
  99823. var h = c.halfHeight;
  99824. var d = c.halfDepth;
  99825. var ox;
  99826. var oy;
  99827. var oz;
  99828. if (ldx < 0) ox = -w;
  99829. else ox = w;
  99830. if (ldy < 0) oy = -h;
  99831. else oy = h;
  99832. if (ldz < 0) oz = -d;
  99833. else oz = d;
  99834. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  99835. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  99836. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  99837. out.init(ldx, ldy, ldz);
  99838. };
  99839. OIMO.BoxCylinderCollisionDetector.prototype.supportPointC = function (c, dx, dy, dz, out) {
  99840. var rot = c.rotation.elements;
  99841. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  99842. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  99843. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  99844. var radx = ldx;
  99845. var radz = ldz;
  99846. var len = radx * radx + radz * radz;
  99847. var rad = c.radius;
  99848. var hh = c.halfHeight;
  99849. var ox;
  99850. var oy;
  99851. var oz;
  99852. if (len == 0) {
  99853. if (ldy < 0) {
  99854. ox = rad;
  99855. oy = -hh;
  99856. oz = 0;
  99857. } else {
  99858. ox = rad;
  99859. oy = hh;
  99860. oz = 0;
  99861. }
  99862. } else {
  99863. len = c.radius / OIMO.sqrt(len);
  99864. if (ldy < 0) {
  99865. ox = radx * len;
  99866. oy = -hh;
  99867. oz = radz * len;
  99868. } else {
  99869. ox = radx * len;
  99870. oy = hh;
  99871. oz = radz * len;
  99872. }
  99873. }
  99874. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  99875. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  99876. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  99877. out.init(ldx, ldy, ldz);
  99878. };
  99879. OIMO.BoxCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  99880. var b;
  99881. var c;
  99882. if (this.flip) {
  99883. b = shape2;
  99884. c = shape1;
  99885. } else {
  99886. b = shape1;
  99887. c = shape2;
  99888. }
  99889. var sep = new OIMO.Vec3();
  99890. var pos = new OIMO.Vec3();
  99891. var dep = new OIMO.Vec3();
  99892. var co;
  99893. if (!this.getSep(b, c, sep, pos, dep)) return;
  99894. var pbx = b.position.x;
  99895. var pby = b.position.y;
  99896. var pbz = b.position.z;
  99897. var pcx = c.position.x;
  99898. var pcy = c.position.y;
  99899. var pcz = c.position.z;
  99900. var bw = b.halfWidth;
  99901. var bh = b.halfHeight;
  99902. var bd = b.halfDepth;
  99903. var ch = c.halfHeight;
  99904. var r = c.radius;
  99905. var D = b.dimentions;
  99906. var nwx = D[0];//b.normalDirectionWidth.x;
  99907. var nwy = D[1];//b.normalDirectionWidth.y;
  99908. var nwz = D[2];//b.normalDirectionWidth.z;
  99909. var nhx = D[3];//b.normalDirectionHeight.x;
  99910. var nhy = D[4];//b.normalDirectionHeight.y;
  99911. var nhz = D[5];//b.normalDirectionHeight.z;
  99912. var ndx = D[6];//b.normalDirectionDepth.x;
  99913. var ndy = D[7];//b.normalDirectionDepth.y;
  99914. var ndz = D[8];//b.normalDirectionDepth.z;
  99915. var dwx = D[9];//b.halfDirectionWidth.x;
  99916. var dwy = D[10];//b.halfDirectionWidth.y;
  99917. var dwz = D[11];//b.halfDirectionWidth.z;
  99918. var dhx = D[12];//b.halfDirectionHeight.x;
  99919. var dhy = D[13];//b.halfDirectionHeight.y;
  99920. var dhz = D[14];//b.halfDirectionHeight.z;
  99921. var ddx = D[15];//b.halfDirectionDepth.x;
  99922. var ddy = D[16];//b.halfDirectionDepth.y;
  99923. var ddz = D[17];//b.halfDirectionDepth.z;
  99924. var ncx = c.normalDirection.x;
  99925. var ncy = c.normalDirection.y;
  99926. var ncz = c.normalDirection.z;
  99927. var dcx = c.halfDirection.x;
  99928. var dcy = c.halfDirection.y;
  99929. var dcz = c.halfDirection.z;
  99930. var nx = sep.x;
  99931. var ny = sep.y;
  99932. var nz = sep.z;
  99933. var dotw = nx * nwx + ny * nwy + nz * nwz;
  99934. var doth = nx * nhx + ny * nhy + nz * nhz;
  99935. var dotd = nx * ndx + ny * ndy + nz * ndz;
  99936. var dotc = nx * ncx + ny * ncy + nz * ncz;
  99937. var right1 = dotw > 0;
  99938. var right2 = doth > 0;
  99939. var right3 = dotd > 0;
  99940. var right4 = dotc > 0;
  99941. if (!right1) dotw = -dotw;
  99942. if (!right2) doth = -doth;
  99943. if (!right3) dotd = -dotd;
  99944. if (!right4) dotc = -dotc;
  99945. var state = 0;
  99946. if (dotc > 0.999) {
  99947. if (dotw > 0.999) {
  99948. if (dotw > dotc) state = 1;
  99949. else state = 4;
  99950. } else if (doth > 0.999) {
  99951. if (doth > dotc) state = 2;
  99952. else state = 4;
  99953. } else if (dotd > 0.999) {
  99954. if (dotd > dotc) state = 3;
  99955. else state = 4;
  99956. } else state = 4;
  99957. } else {
  99958. if (dotw > 0.999) state = 1;
  99959. else if (doth > 0.999) state = 2;
  99960. else if (dotd > 0.999) state = 3;
  99961. }
  99962. var cbx;
  99963. var cby;
  99964. var cbz;
  99965. var ccx;
  99966. var ccy;
  99967. var ccz;
  99968. var r00;
  99969. var r01;
  99970. var r02;
  99971. var r10;
  99972. var r11;
  99973. var r12;
  99974. var r20;
  99975. var r21;
  99976. var r22;
  99977. var px;
  99978. var py;
  99979. var pz;
  99980. var pd;
  99981. var dot;
  99982. var len;
  99983. var tx;
  99984. var ty;
  99985. var tz;
  99986. var td;
  99987. var dx;
  99988. var dy;
  99989. var dz;
  99990. var d1x;
  99991. var d1y;
  99992. var d1z;
  99993. var d2x;
  99994. var d2y;
  99995. var d2z;
  99996. var sx;
  99997. var sy;
  99998. var sz;
  99999. var sd;
  100000. var ex;
  100001. var ey;
  100002. var ez;
  100003. var ed;
  100004. var dot1;
  100005. var dot2;
  100006. var t1;
  100007. var t2;
  100008. var dir1x;
  100009. var dir1y;
  100010. var dir1z;
  100011. var dir2x;
  100012. var dir2y;
  100013. var dir2z;
  100014. var dir1l;
  100015. var dir2l;
  100016. if (state == 0) {
  100017. //manifold.addPoint(pos.x,pos.y,pos.z,nx,ny,nz,dep.x,b,c,0,0,false);
  100018. manifold.addPoint(pos.x, pos.y, pos.z, nx, ny, nz, dep.x, this.flip);
  100019. } else if (state == 4) {
  100020. if (right4) {
  100021. ccx = pcx - dcx;
  100022. ccy = pcy - dcy;
  100023. ccz = pcz - dcz;
  100024. nx = -ncx;
  100025. ny = -ncy;
  100026. nz = -ncz;
  100027. } else {
  100028. ccx = pcx + dcx;
  100029. ccy = pcy + dcy;
  100030. ccz = pcz + dcz;
  100031. nx = ncx;
  100032. ny = ncy;
  100033. nz = ncz;
  100034. }
  100035. var v1x;
  100036. var v1y;
  100037. var v1z;
  100038. var v2x;
  100039. var v2y;
  100040. var v2z;
  100041. var v3x;
  100042. var v3y;
  100043. var v3z;
  100044. var v4x;
  100045. var v4y;
  100046. var v4z;
  100047. dot = 1;
  100048. state = 0;
  100049. dot1 = nwx * nx + nwy * ny + nwz * nz;
  100050. if (dot1 < dot) {
  100051. dot = dot1;
  100052. state = 0;
  100053. }
  100054. if (-dot1 < dot) {
  100055. dot = -dot1;
  100056. state = 1;
  100057. }
  100058. dot1 = nhx * nx + nhy * ny + nhz * nz;
  100059. if (dot1 < dot) {
  100060. dot = dot1;
  100061. state = 2;
  100062. }
  100063. if (-dot1 < dot) {
  100064. dot = -dot1;
  100065. state = 3;
  100066. }
  100067. dot1 = ndx * nx + ndy * ny + ndz * nz;
  100068. if (dot1 < dot) {
  100069. dot = dot1;
  100070. state = 4;
  100071. }
  100072. if (-dot1 < dot) {
  100073. dot = -dot1;
  100074. state = 5;
  100075. }
  100076. var v = b.elements;
  100077. switch (state) {
  100078. case 0:
  100079. //v=b.vertex1;
  100080. v1x = v[0];//v.x;
  100081. v1y = v[1];//v.y;
  100082. v1z = v[2];//v.z;
  100083. //v=b.vertex3;
  100084. v2x = v[6];//v.x;
  100085. v2y = v[7];//v.y;
  100086. v2z = v[8];//v.z;
  100087. //v=b.vertex4;
  100088. v3x = v[9];//v.x;
  100089. v3y = v[10];//v.y;
  100090. v3z = v[11];//v.z;
  100091. //v=b.vertex2;
  100092. v4x = v[3];//v.x;
  100093. v4y = v[4];//v.y;
  100094. v4z = v[5];//v.z;
  100095. break;
  100096. case 1:
  100097. //v=b.vertex6;
  100098. v1x = v[15];//v.x;
  100099. v1y = v[16];//v.y;
  100100. v1z = v[17];//v.z;
  100101. //v=b.vertex8;
  100102. v2x = v[21];//v.x;
  100103. v2y = v[22];//v.y;
  100104. v2z = v[23];//v.z;
  100105. //v=b.vertex7;
  100106. v3x = v[18];//v.x;
  100107. v3y = v[19];//v.y;
  100108. v3z = v[20];//v.z;
  100109. //v=b.vertex5;
  100110. v4x = v[12];//v.x;
  100111. v4y = v[13];//v.y;
  100112. v4z = v[14];//v.z;
  100113. break;
  100114. case 2:
  100115. //v=b.vertex5;
  100116. v1x = v[12];//v.x;
  100117. v1y = v[13];//v.y;
  100118. v1z = v[14];//v.z;
  100119. //v=b.vertex1;
  100120. v2x = v[0];//v.x;
  100121. v2y = v[1];//v.y;
  100122. v2z = v[2];//v.z;
  100123. //v=b.vertex2;
  100124. v3x = v[3];//v.x;
  100125. v3y = v[4];//v.y;
  100126. v3z = v[5];//v.z;
  100127. //v=b.vertex6;
  100128. v4x = v[15];//v.x;
  100129. v4y = v[16];//v.y;
  100130. v4z = v[17];//v.z;
  100131. break;
  100132. case 3:
  100133. //v=b.vertex8;
  100134. v1x = v[21];//v.x;
  100135. v1y = v[22];//v.y;
  100136. v1z = v[23];//v.z;
  100137. //v=b.vertex4;
  100138. v2x = v[9];//v.x;
  100139. v2y = v[10];//v.y;
  100140. v2z = v[11];//v.z;
  100141. //v=b.vertex3;
  100142. v3x = v[6];//v.x;
  100143. v3y = v[7];//v.y;
  100144. v3z = v[8];//v.z;
  100145. //v=b.vertex7;
  100146. v4x = v[18];//v.x;
  100147. v4y = v[19];//v.y;
  100148. v4z = v[20];//v.z;
  100149. break;
  100150. case 4:
  100151. //v=b.vertex5;
  100152. v1x = v[12];//v.x;
  100153. v1y = v[13];//v.y;
  100154. v1z = v[14];//v.z;
  100155. //v=b.vertex7;
  100156. v2x = v[18];//v.x;
  100157. v2y = v[19];//v.y;
  100158. v2z = v[20];//v.z;
  100159. //v=b.vertex3;
  100160. v3x = v[6];//v.x;
  100161. v3y = v[7];//v.y;
  100162. v3z = v[8];//v.z;
  100163. //v=b.vertex1;
  100164. v4x = v[0];//v.x;
  100165. v4y = v[1];//v.y;
  100166. v4z = v[2];//v.z;
  100167. break;
  100168. case 5:
  100169. //v=b.vertex2;
  100170. v1x = v[3];//v.x;
  100171. v1y = v[4];//v.y;
  100172. v1z = v[5];//v.z;
  100173. //v=b.vertex4;
  100174. v2x = v[9];//v.x;
  100175. v2y = v[10];//v.y;
  100176. v2z = v[11];//v.z;
  100177. //v=b.vertex8;
  100178. v3x = v[21];//v.x;
  100179. v3y = v[22];//v.y;
  100180. v3z = v[23];//v.z;
  100181. //v=b.vertex6;
  100182. v4x = v[15];//v.x;
  100183. v4y = v[16];//v.y;
  100184. v4z = v[17];//v.z;
  100185. break;
  100186. }
  100187. pd = nx * (v1x - ccx) + ny * (v1y - ccy) + nz * (v1z - ccz);
  100188. if (pd <= 0) manifold.addPoint(v1x, v1y, v1z, -nx, -ny, -nz, pd, this.flip);
  100189. pd = nx * (v2x - ccx) + ny * (v2y - ccy) + nz * (v2z - ccz);
  100190. if (pd <= 0) manifold.addPoint(v2x, v2y, v2z, -nx, -ny, -nz, pd, this.flip);
  100191. pd = nx * (v3x - ccx) + ny * (v3y - ccy) + nz * (v3z - ccz);
  100192. if (pd <= 0) manifold.addPoint(v3x, v3y, v3z, -nx, -ny, -nz, pd, this.flip);
  100193. pd = nx * (v4x - ccx) + ny * (v4y - ccy) + nz * (v4z - ccz);
  100194. if (pd <= 0) manifold.addPoint(v4x, v4y, v4z, -nx, -ny, -nz, pd, this.flip);
  100195. } else {
  100196. switch (state) {
  100197. case 1:
  100198. if (right1) {
  100199. cbx = pbx + dwx;
  100200. cby = pby + dwy;
  100201. cbz = pbz + dwz;
  100202. nx = nwx;
  100203. ny = nwy;
  100204. nz = nwz;
  100205. } else {
  100206. cbx = pbx - dwx;
  100207. cby = pby - dwy;
  100208. cbz = pbz - dwz;
  100209. nx = -nwx;
  100210. ny = -nwy;
  100211. nz = -nwz;
  100212. }
  100213. dir1x = nhx;
  100214. dir1y = nhy;
  100215. dir1z = nhz;
  100216. dir1l = bh;
  100217. dir2x = ndx;
  100218. dir2y = ndy;
  100219. dir2z = ndz;
  100220. dir2l = bd;
  100221. break;
  100222. case 2:
  100223. if (right2) {
  100224. cbx = pbx + dhx;
  100225. cby = pby + dhy;
  100226. cbz = pbz + dhz;
  100227. nx = nhx;
  100228. ny = nhy;
  100229. nz = nhz;
  100230. } else {
  100231. cbx = pbx - dhx;
  100232. cby = pby - dhy;
  100233. cbz = pbz - dhz;
  100234. nx = -nhx;
  100235. ny = -nhy;
  100236. nz = -nhz;
  100237. }
  100238. dir1x = nwx;
  100239. dir1y = nwy;
  100240. dir1z = nwz;
  100241. dir1l = bw;
  100242. dir2x = ndx;
  100243. dir2y = ndy;
  100244. dir2z = ndz;
  100245. dir2l = bd;
  100246. break;
  100247. case 3:
  100248. if (right3) {
  100249. cbx = pbx + ddx;
  100250. cby = pby + ddy;
  100251. cbz = pbz + ddz;
  100252. nx = ndx;
  100253. ny = ndy;
  100254. nz = ndz;
  100255. } else {
  100256. cbx = pbx - ddx;
  100257. cby = pby - ddy;
  100258. cbz = pbz - ddz;
  100259. nx = -ndx;
  100260. ny = -ndy;
  100261. nz = -ndz;
  100262. }
  100263. dir1x = nwx;
  100264. dir1y = nwy;
  100265. dir1z = nwz;
  100266. dir1l = bw;
  100267. dir2x = nhx;
  100268. dir2y = nhy;
  100269. dir2z = nhz;
  100270. dir2l = bh;
  100271. break;
  100272. }
  100273. dot = nx * ncx + ny * ncy + nz * ncz;
  100274. if (dot < 0) len = ch;
  100275. else len = -ch;
  100276. ccx = pcx + len * ncx;
  100277. ccy = pcy + len * ncy;
  100278. ccz = pcz + len * ncz;
  100279. if (dotc >= 0.999999) {
  100280. tx = -ny;
  100281. ty = nz;
  100282. tz = nx;
  100283. } else {
  100284. tx = nx;
  100285. ty = ny;
  100286. tz = nz;
  100287. }
  100288. len = tx * ncx + ty * ncy + tz * ncz;
  100289. dx = len * ncx - tx;
  100290. dy = len * ncy - ty;
  100291. dz = len * ncz - tz;
  100292. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  100293. if (len == 0) return;
  100294. len = r / len;
  100295. dx *= len;
  100296. dy *= len;
  100297. dz *= len;
  100298. tx = ccx + dx;
  100299. ty = ccy + dy;
  100300. tz = ccz + dz;
  100301. if (dot < -0.96 || dot > 0.96) {
  100302. r00 = ncx * ncx * 1.5 - 0.5;
  100303. r01 = ncx * ncy * 1.5 - ncz * 0.866025403;
  100304. r02 = ncx * ncz * 1.5 + ncy * 0.866025403;
  100305. r10 = ncy * ncx * 1.5 + ncz * 0.866025403;
  100306. r11 = ncy * ncy * 1.5 - 0.5;
  100307. r12 = ncy * ncz * 1.5 - ncx * 0.866025403;
  100308. r20 = ncz * ncx * 1.5 - ncy * 0.866025403;
  100309. r21 = ncz * ncy * 1.5 + ncx * 0.866025403;
  100310. r22 = ncz * ncz * 1.5 - 0.5;
  100311. px = tx;
  100312. py = ty;
  100313. pz = tz;
  100314. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  100315. tx = px - pd * nx - cbx;
  100316. ty = py - pd * ny - cby;
  100317. tz = pz - pd * nz - cbz;
  100318. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  100319. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  100320. if (sd < -dir1l) sd = -dir1l;
  100321. else if (sd > dir1l) sd = dir1l;
  100322. if (ed < -dir2l) ed = -dir2l;
  100323. else if (ed > dir2l) ed = dir2l;
  100324. tx = sd * dir1x + ed * dir2x;
  100325. ty = sd * dir1y + ed * dir2y;
  100326. tz = sd * dir1z + ed * dir2z;
  100327. px = cbx + tx;
  100328. py = cby + ty;
  100329. pz = cbz + tz;
  100330. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  100331. px = dx * r00 + dy * r01 + dz * r02;
  100332. py = dx * r10 + dy * r11 + dz * r12;
  100333. pz = dx * r20 + dy * r21 + dz * r22;
  100334. px = (dx = px) + ccx;
  100335. py = (dy = py) + ccy;
  100336. pz = (dz = pz) + ccz;
  100337. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  100338. if (pd <= 0) {
  100339. tx = px - pd * nx - cbx;
  100340. ty = py - pd * ny - cby;
  100341. tz = pz - pd * nz - cbz;
  100342. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  100343. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  100344. if (sd < -dir1l) sd = -dir1l;
  100345. else if (sd > dir1l) sd = dir1l;
  100346. if (ed < -dir2l) ed = -dir2l;
  100347. else if (ed > dir2l) ed = dir2l;
  100348. tx = sd * dir1x + ed * dir2x;
  100349. ty = sd * dir1y + ed * dir2y;
  100350. tz = sd * dir1z + ed * dir2z;
  100351. px = cbx + tx;
  100352. py = cby + ty;
  100353. pz = cbz + tz;
  100354. //manifold.addPoint(px,py,pz,nx,ny,nz,pd,b,c,2,0,false);
  100355. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  100356. }
  100357. px = dx * r00 + dy * r01 + dz * r02;
  100358. py = dx * r10 + dy * r11 + dz * r12;
  100359. pz = dx * r20 + dy * r21 + dz * r22;
  100360. px = (dx = px) + ccx;
  100361. py = (dy = py) + ccy;
  100362. pz = (dz = pz) + ccz;
  100363. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  100364. if (pd <= 0) {
  100365. tx = px - pd * nx - cbx;
  100366. ty = py - pd * ny - cby;
  100367. tz = pz - pd * nz - cbz;
  100368. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  100369. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  100370. if (sd < -dir1l) sd = -dir1l;
  100371. else if (sd > dir1l) sd = dir1l;
  100372. if (ed < -dir2l) ed = -dir2l;
  100373. else if (ed > dir2l) ed = dir2l;
  100374. tx = sd * dir1x + ed * dir2x;
  100375. ty = sd * dir1y + ed * dir2y;
  100376. tz = sd * dir1z + ed * dir2z;
  100377. px = cbx + tx;
  100378. py = cby + ty;
  100379. pz = cbz + tz;
  100380. //manifold.addPoint(px,py,pz,nx,ny,nz,pd,b,c,3,0,false);
  100381. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  100382. }
  100383. } else {
  100384. sx = tx;
  100385. sy = ty;
  100386. sz = tz;
  100387. sd = nx * (sx - cbx) + ny * (sy - cby) + nz * (sz - cbz);
  100388. sx -= sd * nx;
  100389. sy -= sd * ny;
  100390. sz -= sd * nz;
  100391. if (dot > 0) {
  100392. ex = tx + dcx * 2;
  100393. ey = ty + dcy * 2;
  100394. ez = tz + dcz * 2;
  100395. } else {
  100396. ex = tx - dcx * 2;
  100397. ey = ty - dcy * 2;
  100398. ez = tz - dcz * 2;
  100399. }
  100400. ed = nx * (ex - cbx) + ny * (ey - cby) + nz * (ez - cbz);
  100401. ex -= ed * nx;
  100402. ey -= ed * ny;
  100403. ez -= ed * nz;
  100404. d1x = sx - cbx;
  100405. d1y = sy - cby;
  100406. d1z = sz - cbz;
  100407. d2x = ex - cbx;
  100408. d2y = ey - cby;
  100409. d2z = ez - cbz;
  100410. tx = ex - sx;
  100411. ty = ey - sy;
  100412. tz = ez - sz;
  100413. td = ed - sd;
  100414. dotw = d1x * dir1x + d1y * dir1y + d1z * dir1z;
  100415. doth = d2x * dir1x + d2y * dir1y + d2z * dir1z;
  100416. dot1 = dotw - dir1l;
  100417. dot2 = doth - dir1l;
  100418. if (dot1 > 0) {
  100419. if (dot2 > 0) return;
  100420. t1 = dot1 / (dot1 - dot2);
  100421. sx = sx + tx * t1;
  100422. sy = sy + ty * t1;
  100423. sz = sz + tz * t1;
  100424. sd = sd + td * t1;
  100425. d1x = sx - cbx;
  100426. d1y = sy - cby;
  100427. d1z = sz - cbz;
  100428. dotw = d1x * dir1x + d1y * dir1y + d1z * dir1z;
  100429. tx = ex - sx;
  100430. ty = ey - sy;
  100431. tz = ez - sz;
  100432. td = ed - sd;
  100433. } else if (dot2 > 0) {
  100434. t1 = dot1 / (dot1 - dot2);
  100435. ex = sx + tx * t1;
  100436. ey = sy + ty * t1;
  100437. ez = sz + tz * t1;
  100438. ed = sd + td * t1;
  100439. d2x = ex - cbx;
  100440. d2y = ey - cby;
  100441. d2z = ez - cbz;
  100442. doth = d2x * dir1x + d2y * dir1y + d2z * dir1z;
  100443. tx = ex - sx;
  100444. ty = ey - sy;
  100445. tz = ez - sz;
  100446. td = ed - sd;
  100447. }
  100448. dot1 = dotw + dir1l;
  100449. dot2 = doth + dir1l;
  100450. if (dot1 < 0) {
  100451. if (dot2 < 0) return;
  100452. t1 = dot1 / (dot1 - dot2);
  100453. sx = sx + tx * t1;
  100454. sy = sy + ty * t1;
  100455. sz = sz + tz * t1;
  100456. sd = sd + td * t1;
  100457. d1x = sx - cbx;
  100458. d1y = sy - cby;
  100459. d1z = sz - cbz;
  100460. tx = ex - sx;
  100461. ty = ey - sy;
  100462. tz = ez - sz;
  100463. td = ed - sd;
  100464. } else if (dot2 < 0) {
  100465. t1 = dot1 / (dot1 - dot2);
  100466. ex = sx + tx * t1;
  100467. ey = sy + ty * t1;
  100468. ez = sz + tz * t1;
  100469. ed = sd + td * t1;
  100470. d2x = ex - cbx;
  100471. d2y = ey - cby;
  100472. d2z = ez - cbz;
  100473. tx = ex - sx;
  100474. ty = ey - sy;
  100475. tz = ez - sz;
  100476. td = ed - sd;
  100477. }
  100478. dotw = d1x * dir2x + d1y * dir2y + d1z * dir2z;
  100479. doth = d2x * dir2x + d2y * dir2y + d2z * dir2z;
  100480. dot1 = dotw - dir2l;
  100481. dot2 = doth - dir2l;
  100482. if (dot1 > 0) {
  100483. if (dot2 > 0) return;
  100484. t1 = dot1 / (dot1 - dot2);
  100485. sx = sx + tx * t1;
  100486. sy = sy + ty * t1;
  100487. sz = sz + tz * t1;
  100488. sd = sd + td * t1;
  100489. d1x = sx - cbx;
  100490. d1y = sy - cby;
  100491. d1z = sz - cbz;
  100492. dotw = d1x * dir2x + d1y * dir2y + d1z * dir2z;
  100493. tx = ex - sx;
  100494. ty = ey - sy;
  100495. tz = ez - sz;
  100496. td = ed - sd;
  100497. } else if (dot2 > 0) {
  100498. t1 = dot1 / (dot1 - dot2);
  100499. ex = sx + tx * t1;
  100500. ey = sy + ty * t1;
  100501. ez = sz + tz * t1;
  100502. ed = sd + td * t1;
  100503. d2x = ex - cbx;
  100504. d2y = ey - cby;
  100505. d2z = ez - cbz;
  100506. doth = d2x * dir2x + d2y * dir2y + d2z * dir2z;
  100507. tx = ex - sx;
  100508. ty = ey - sy;
  100509. tz = ez - sz;
  100510. td = ed - sd;
  100511. }
  100512. dot1 = dotw + dir2l;
  100513. dot2 = doth + dir2l;
  100514. if (dot1 < 0) {
  100515. if (dot2 < 0) return;
  100516. t1 = dot1 / (dot1 - dot2);
  100517. sx = sx + tx * t1;
  100518. sy = sy + ty * t1;
  100519. sz = sz + tz * t1;
  100520. sd = sd + td * t1;
  100521. } else if (dot2 < 0) {
  100522. t1 = dot1 / (dot1 - dot2);
  100523. ex = sx + tx * t1;
  100524. ey = sy + ty * t1;
  100525. ez = sz + tz * t1;
  100526. ed = sd + td * t1;
  100527. }
  100528. if (sd < 0) {
  100529. //manifold.addPoint(sx,sy,sz,nx,ny,nz,sd,b,c,1,0,false);
  100530. manifold.addPoint(sx, sy, sz, nx, ny, nz, sd, this.flip);
  100531. }
  100532. if (ed < 0) {
  100533. //manifold.addPoint(ex,ey,ez,nx,ny,nz,ed,b,c,4,0,false);
  100534. manifold.addPoint(ex, ey, ez, nx, ny, nz, ed, this.flip);
  100535. }
  100536. }
  100537. }
  100538. };
  100539. OIMO.CylinderCylinderCollisionDetector = function () {
  100540. OIMO.CollisionDetector.call(this);
  100541. };
  100542. OIMO.CylinderCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  100543. OIMO.CylinderCylinderCollisionDetector.prototype.constructor = OIMO.CylinderCylinderCollisionDetector;
  100544. OIMO.CylinderCylinderCollisionDetector.prototype.getSep = function (c1, c2, sep, pos, dep) {
  100545. var t1x;
  100546. var t1y;
  100547. var t1z;
  100548. var t2x;
  100549. var t2y;
  100550. var t2z;
  100551. var sup = new OIMO.Vec3();
  100552. var len;
  100553. var p1x;
  100554. var p1y;
  100555. var p1z;
  100556. var p2x;
  100557. var p2y;
  100558. var p2z;
  100559. var v01x = c1.position.x;
  100560. var v01y = c1.position.y;
  100561. var v01z = c1.position.z;
  100562. var v02x = c2.position.x;
  100563. var v02y = c2.position.y;
  100564. var v02z = c2.position.z;
  100565. var v0x = v02x - v01x;
  100566. var v0y = v02y - v01y;
  100567. var v0z = v02z - v01z;
  100568. if (v0x * v0x + v0y * v0y + v0z * v0z == 0) v0y = 0.001;
  100569. var nx = -v0x;
  100570. var ny = -v0y;
  100571. var nz = -v0z;
  100572. this.supportPoint(c1, -nx, -ny, -nz, sup);
  100573. var v11x = sup.x;
  100574. var v11y = sup.y;
  100575. var v11z = sup.z;
  100576. this.supportPoint(c2, nx, ny, nz, sup);
  100577. var v12x = sup.x;
  100578. var v12y = sup.y;
  100579. var v12z = sup.z;
  100580. var v1x = v12x - v11x;
  100581. var v1y = v12y - v11y;
  100582. var v1z = v12z - v11z;
  100583. if (v1x * nx + v1y * ny + v1z * nz <= 0) {
  100584. return false;
  100585. }
  100586. nx = v1y * v0z - v1z * v0y;
  100587. ny = v1z * v0x - v1x * v0z;
  100588. nz = v1x * v0y - v1y * v0x;
  100589. if (nx * nx + ny * ny + nz * nz == 0) {
  100590. sep.init(v1x - v0x, v1y - v0y, v1z - v0z);
  100591. sep.normalize(sep);
  100592. pos.init((v11x + v12x) * 0.5, (v11y + v12y) * 0.5, (v11z + v12z) * 0.5);
  100593. return true;
  100594. }
  100595. this.supportPoint(c1, -nx, -ny, -nz, sup);
  100596. var v21x = sup.x;
  100597. var v21y = sup.y;
  100598. var v21z = sup.z;
  100599. this.supportPoint(c2, nx, ny, nz, sup);
  100600. var v22x = sup.x;
  100601. var v22y = sup.y;
  100602. var v22z = sup.z;
  100603. var v2x = v22x - v21x;
  100604. var v2y = v22y - v21y;
  100605. var v2z = v22z - v21z;
  100606. if (v2x * nx + v2y * ny + v2z * nz <= 0) {
  100607. return false;
  100608. }
  100609. t1x = v1x - v0x;
  100610. t1y = v1y - v0y;
  100611. t1z = v1z - v0z;
  100612. t2x = v2x - v0x;
  100613. t2y = v2y - v0y;
  100614. t2z = v2z - v0z;
  100615. nx = t1y * t2z - t1z * t2y;
  100616. ny = t1z * t2x - t1x * t2z;
  100617. nz = t1x * t2y - t1y * t2x;
  100618. if (nx * v0x + ny * v0y + nz * v0z > 0) {
  100619. t1x = v1x;
  100620. t1y = v1y;
  100621. t1z = v1z;
  100622. v1x = v2x;
  100623. v1y = v2y;
  100624. v1z = v2z;
  100625. v2x = t1x;
  100626. v2y = t1y;
  100627. v2z = t1z;
  100628. t1x = v11x;
  100629. t1y = v11y;
  100630. t1z = v11z;
  100631. v11x = v21x;
  100632. v11y = v21y;
  100633. v11z = v21z;
  100634. v21x = t1x;
  100635. v21y = t1y;
  100636. v21z = t1z;
  100637. t1x = v12x;
  100638. t1y = v12y;
  100639. t1z = v12z;
  100640. v12x = v22x;
  100641. v12y = v22y;
  100642. v12z = v22z;
  100643. v22x = t1x;
  100644. v22y = t1y;
  100645. v22z = t1z;
  100646. nx = -nx;
  100647. ny = -ny;
  100648. nz = -nz;
  100649. }
  100650. var iterations = 0;
  100651. while (true) {
  100652. if (++iterations > 100) {
  100653. return false;
  100654. }
  100655. this.supportPoint(c1, -nx, -ny, -nz, sup);
  100656. var v31x = sup.x;
  100657. var v31y = sup.y;
  100658. var v31z = sup.z;
  100659. this.supportPoint(c2, nx, ny, nz, sup);
  100660. var v32x = sup.x;
  100661. var v32y = sup.y;
  100662. var v32z = sup.z;
  100663. var v3x = v32x - v31x;
  100664. var v3y = v32y - v31y;
  100665. var v3z = v32z - v31z;
  100666. if (v3x * nx + v3y * ny + v3z * nz <= 0) {
  100667. return false;
  100668. }
  100669. if ((v1y * v3z - v1z * v3y) * v0x + (v1z * v3x - v1x * v3z) * v0y + (v1x * v3y - v1y * v3x) * v0z < 0) {
  100670. v2x = v3x;
  100671. v2y = v3y;
  100672. v2z = v3z;
  100673. v21x = v31x;
  100674. v21y = v31y;
  100675. v21z = v31z;
  100676. v22x = v32x;
  100677. v22y = v32y;
  100678. v22z = v32z;
  100679. t1x = v1x - v0x;
  100680. t1y = v1y - v0y;
  100681. t1z = v1z - v0z;
  100682. t2x = v3x - v0x;
  100683. t2y = v3y - v0y;
  100684. t2z = v3z - v0z;
  100685. nx = t1y * t2z - t1z * t2y;
  100686. ny = t1z * t2x - t1x * t2z;
  100687. nz = t1x * t2y - t1y * t2x;
  100688. continue;
  100689. }
  100690. if ((v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z < 0) {
  100691. v1x = v3x;
  100692. v1y = v3y;
  100693. v1z = v3z;
  100694. v11x = v31x;
  100695. v11y = v31y;
  100696. v11z = v31z;
  100697. v12x = v32x;
  100698. v12y = v32y;
  100699. v12z = v32z;
  100700. t1x = v3x - v0x;
  100701. t1y = v3y - v0y;
  100702. t1z = v3z - v0z;
  100703. t2x = v2x - v0x;
  100704. t2y = v2y - v0y;
  100705. t2z = v2z - v0z;
  100706. nx = t1y * t2z - t1z * t2y;
  100707. ny = t1z * t2x - t1x * t2z;
  100708. nz = t1x * t2y - t1y * t2x;
  100709. continue;
  100710. }
  100711. var hit = false;
  100712. while (true) {
  100713. t1x = v2x - v1x;
  100714. t1y = v2y - v1y;
  100715. t1z = v2z - v1z;
  100716. t2x = v3x - v1x;
  100717. t2y = v3y - v1y;
  100718. t2z = v3z - v1z;
  100719. nx = t1y * t2z - t1z * t2y;
  100720. ny = t1z * t2x - t1x * t2z;
  100721. nz = t1x * t2y - t1y * t2x;
  100722. len = 1 / OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  100723. nx *= len;
  100724. ny *= len;
  100725. nz *= len;
  100726. if (nx * v1x + ny * v1y + nz * v1z >= 0 && !hit) {
  100727. var b0 = (v1y * v2z - v1z * v2y) * v3x + (v1z * v2x - v1x * v2z) * v3y + (v1x * v2y - v1y * v2x) * v3z;
  100728. var b1 = (v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z;
  100729. var b2 = (v0y * v1z - v0z * v1y) * v3x + (v0z * v1x - v0x * v1z) * v3y + (v0x * v1y - v0y * v1x) * v3z;
  100730. var b3 = (v2y * v1z - v2z * v1y) * v0x + (v2z * v1x - v2x * v1z) * v0y + (v2x * v1y - v2y * v1x) * v0z;
  100731. var sum = b0 + b1 + b2 + b3;
  100732. if (sum <= 0) {
  100733. b0 = 0;
  100734. b1 = (v2y * v3z - v2z * v3y) * nx + (v2z * v3x - v2x * v3z) * ny + (v2x * v3y - v2y * v3x) * nz;
  100735. b2 = (v3y * v2z - v3z * v2y) * nx + (v3z * v2x - v3x * v2z) * ny + (v3x * v2y - v3y * v2x) * nz;
  100736. b3 = (v1y * v2z - v1z * v2y) * nx + (v1z * v2x - v1x * v2z) * ny + (v1x * v2y - v1y * v2x) * nz;
  100737. sum = b1 + b2 + b3;
  100738. }
  100739. var inv = 1 / sum;
  100740. p1x = (v01x * b0 + v11x * b1 + v21x * b2 + v31x * b3) * inv;
  100741. p1y = (v01y * b0 + v11y * b1 + v21y * b2 + v31y * b3) * inv;
  100742. p1z = (v01z * b0 + v11z * b1 + v21z * b2 + v31z * b3) * inv;
  100743. p2x = (v02x * b0 + v12x * b1 + v22x * b2 + v32x * b3) * inv;
  100744. p2y = (v02y * b0 + v12y * b1 + v22y * b2 + v32y * b3) * inv;
  100745. p2z = (v02z * b0 + v12z * b1 + v22z * b2 + v32z * b3) * inv;
  100746. hit = true;
  100747. }
  100748. this.supportPoint(c1, -nx, -ny, -nz, sup);
  100749. var v41x = sup.x;
  100750. var v41y = sup.y;
  100751. var v41z = sup.z;
  100752. this.supportPoint(c2, nx, ny, nz, sup);
  100753. var v42x = sup.x;
  100754. var v42y = sup.y;
  100755. var v42z = sup.z;
  100756. var v4x = v42x - v41x;
  100757. var v4y = v42y - v41y;
  100758. var v4z = v42z - v41z;
  100759. var separation = -(v4x * nx + v4y * ny + v4z * nz);
  100760. if ((v4x - v3x) * nx + (v4y - v3y) * ny + (v4z - v3z) * nz <= 0.01 || separation >= 0) {
  100761. if (hit) {
  100762. sep.init(-nx, -ny, -nz);
  100763. pos.init((p1x + p2x) * 0.5, (p1y + p2y) * 0.5, (p1z + p2z) * 0.5);
  100764. dep.x = separation;
  100765. return true;
  100766. }
  100767. return false;
  100768. }
  100769. if (
  100770. (v4y * v1z - v4z * v1y) * v0x +
  100771. (v4z * v1x - v4x * v1z) * v0y +
  100772. (v4x * v1y - v4y * v1x) * v0z < 0
  100773. ) {
  100774. if (
  100775. (v4y * v2z - v4z * v2y) * v0x +
  100776. (v4z * v2x - v4x * v2z) * v0y +
  100777. (v4x * v2y - v4y * v2x) * v0z < 0
  100778. ) {
  100779. v1x = v4x;
  100780. v1y = v4y;
  100781. v1z = v4z;
  100782. v11x = v41x;
  100783. v11y = v41y;
  100784. v11z = v41z;
  100785. v12x = v42x;
  100786. v12y = v42y;
  100787. v12z = v42z;
  100788. } else {
  100789. v3x = v4x;
  100790. v3y = v4y;
  100791. v3z = v4z;
  100792. v31x = v41x;
  100793. v31y = v41y;
  100794. v31z = v41z;
  100795. v32x = v42x;
  100796. v32y = v42y;
  100797. v32z = v42z;
  100798. }
  100799. } else {
  100800. if (
  100801. (v4y * v3z - v4z * v3y) * v0x +
  100802. (v4z * v3x - v4x * v3z) * v0y +
  100803. (v4x * v3y - v4y * v3x) * v0z < 0
  100804. ) {
  100805. v2x = v4x;
  100806. v2y = v4y;
  100807. v2z = v4z;
  100808. v21x = v41x;
  100809. v21y = v41y;
  100810. v21z = v41z;
  100811. v22x = v42x;
  100812. v22y = v42y;
  100813. v22z = v42z;
  100814. } else {
  100815. v1x = v4x;
  100816. v1y = v4y;
  100817. v1z = v4z;
  100818. v11x = v41x;
  100819. v11y = v41y;
  100820. v11z = v41z;
  100821. v12x = v42x;
  100822. v12y = v42y;
  100823. v12z = v42z;
  100824. }
  100825. }
  100826. }
  100827. }
  100828. //return false;
  100829. };
  100830. OIMO.CylinderCylinderCollisionDetector.prototype.supportPoint = function (c, dx, dy, dz, out) {
  100831. var rot = c.rotation.elements;
  100832. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  100833. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  100834. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  100835. var radx = ldx;
  100836. var radz = ldz;
  100837. var len = radx * radx + radz * radz;
  100838. var rad = c.radius;
  100839. var hh = c.halfHeight;
  100840. var ox;
  100841. var oy;
  100842. var oz;
  100843. if (len == 0) {
  100844. if (ldy < 0) {
  100845. ox = rad;
  100846. oy = -hh;
  100847. oz = 0;
  100848. } else {
  100849. ox = rad;
  100850. oy = hh;
  100851. oz = 0;
  100852. }
  100853. } else {
  100854. len = c.radius / OIMO.sqrt(len);
  100855. if (ldy < 0) {
  100856. ox = radx * len;
  100857. oy = -hh;
  100858. oz = radz * len;
  100859. } else {
  100860. ox = radx * len;
  100861. oy = hh;
  100862. oz = radz * len;
  100863. }
  100864. }
  100865. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  100866. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  100867. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  100868. out.init(ldx, ldy, ldz);
  100869. };
  100870. OIMO.CylinderCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  100871. var c1;
  100872. var c2;
  100873. if (shape1.id < shape2.id) {
  100874. c1 = shape1;
  100875. c2 = shape2;
  100876. } else {
  100877. c1 = shape2;
  100878. c2 = shape1;
  100879. }
  100880. var p1 = c1.position;
  100881. var p2 = c2.position;
  100882. var p1x = p1.x;
  100883. var p1y = p1.y;
  100884. var p1z = p1.z;
  100885. var p2x = p2.x;
  100886. var p2y = p2.y;
  100887. var p2z = p2.z;
  100888. var h1 = c1.halfHeight;
  100889. var h2 = c2.halfHeight;
  100890. var n1 = c1.normalDirection;
  100891. var n2 = c2.normalDirection;
  100892. var d1 = c1.halfDirection;
  100893. var d2 = c2.halfDirection;
  100894. var r1 = c1.radius;
  100895. var r2 = c2.radius;
  100896. var n1x = n1.x;
  100897. var n1y = n1.y;
  100898. var n1z = n1.z;
  100899. var n2x = n2.x;
  100900. var n2y = n2.y;
  100901. var n2z = n2.z;
  100902. var d1x = d1.x;
  100903. var d1y = d1.y;
  100904. var d1z = d1.z;
  100905. var d2x = d2.x;
  100906. var d2y = d2.y;
  100907. var d2z = d2.z;
  100908. var dx = p1x - p2x;
  100909. var dy = p1y - p2y;
  100910. var dz = p1z - p2z;
  100911. var len;
  100912. var len1;
  100913. var len2;
  100914. var c;
  100915. var c1x;
  100916. var c1y;
  100917. var c1z;
  100918. var c2x;
  100919. var c2y;
  100920. var c2z;
  100921. var tx;
  100922. var ty;
  100923. var tz;
  100924. var sx;
  100925. var sy;
  100926. var sz;
  100927. var ex;
  100928. var ey;
  100929. var ez;
  100930. var depth1;
  100931. var depth2;
  100932. var dot;
  100933. var t1;
  100934. var t2;
  100935. var sep = new OIMO.Vec3();
  100936. var pos = new OIMO.Vec3();
  100937. var dep = new OIMO.Vec3();
  100938. if (!this.getSep(c1, c2, sep, pos, dep)) return;
  100939. var dot1 = sep.x * n1x + sep.y * n1y + sep.z * n1z;
  100940. var dot2 = sep.x * n2x + sep.y * n2y + sep.z * n2z;
  100941. var right1 = dot1 > 0;
  100942. var right2 = dot2 > 0;
  100943. if (!right1) dot1 = -dot1;
  100944. if (!right2) dot2 = -dot2;
  100945. var state = 0;
  100946. if (dot1 > 0.999 || dot2 > 0.999) {
  100947. if (dot1 > dot2) state = 1;
  100948. else state = 2;
  100949. }
  100950. var nx;
  100951. var ny;
  100952. var nz;
  100953. var depth = dep.x;
  100954. var r00;
  100955. var r01;
  100956. var r02;
  100957. var r10;
  100958. var r11;
  100959. var r12;
  100960. var r20;
  100961. var r21;
  100962. var r22;
  100963. var px;
  100964. var py;
  100965. var pz;
  100966. var pd;
  100967. var a;
  100968. var b;
  100969. var e;
  100970. var f;
  100971. nx = sep.x;
  100972. ny = sep.y;
  100973. nz = sep.z;
  100974. switch (state) {
  100975. case 0:
  100976. manifold.addPoint(pos.x, pos.y, pos.z, nx, ny, nz, depth, false);
  100977. break;
  100978. case 1:
  100979. if (right1) {
  100980. c1x = p1x + d1x;
  100981. c1y = p1y + d1y;
  100982. c1z = p1z + d1z;
  100983. nx = n1x;
  100984. ny = n1y;
  100985. nz = n1z;
  100986. } else {
  100987. c1x = p1x - d1x;
  100988. c1y = p1y - d1y;
  100989. c1z = p1z - d1z;
  100990. nx = -n1x;
  100991. ny = -n1y;
  100992. nz = -n1z;
  100993. }
  100994. dot = nx * n2x + ny * n2y + nz * n2z;
  100995. if (dot < 0) len = h2;
  100996. else len = -h2;
  100997. c2x = p2x + len * n2x;
  100998. c2y = p2y + len * n2y;
  100999. c2z = p2z + len * n2z;
  101000. if (dot2 >= 0.999999) {
  101001. tx = -ny;
  101002. ty = nz;
  101003. tz = nx;
  101004. } else {
  101005. tx = nx;
  101006. ty = ny;
  101007. tz = nz;
  101008. }
  101009. len = tx * n2x + ty * n2y + tz * n2z;
  101010. dx = len * n2x - tx;
  101011. dy = len * n2y - ty;
  101012. dz = len * n2z - tz;
  101013. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  101014. if (len == 0) break;
  101015. len = r2 / len;
  101016. dx *= len;
  101017. dy *= len;
  101018. dz *= len;
  101019. tx = c2x + dx;
  101020. ty = c2y + dy;
  101021. tz = c2z + dz;
  101022. if (dot < -0.96 || dot > 0.96) {
  101023. r00 = n2x * n2x * 1.5 - 0.5;
  101024. r01 = n2x * n2y * 1.5 - n2z * 0.866025403;
  101025. r02 = n2x * n2z * 1.5 + n2y * 0.866025403;
  101026. r10 = n2y * n2x * 1.5 + n2z * 0.866025403;
  101027. r11 = n2y * n2y * 1.5 - 0.5;
  101028. r12 = n2y * n2z * 1.5 - n2x * 0.866025403;
  101029. r20 = n2z * n2x * 1.5 - n2y * 0.866025403;
  101030. r21 = n2z * n2y * 1.5 + n2x * 0.866025403;
  101031. r22 = n2z * n2z * 1.5 - 0.5;
  101032. px = tx;
  101033. py = ty;
  101034. pz = tz;
  101035. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  101036. tx = px - pd * nx - c1x;
  101037. ty = py - pd * ny - c1y;
  101038. tz = pz - pd * nz - c1z;
  101039. len = tx * tx + ty * ty + tz * tz;
  101040. if (len > r1 * r1) {
  101041. len = r1 / OIMO.sqrt(len);
  101042. tx *= len;
  101043. ty *= len;
  101044. tz *= len;
  101045. }
  101046. px = c1x + tx;
  101047. py = c1y + ty;
  101048. pz = c1z + tz;
  101049. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  101050. px = dx * r00 + dy * r01 + dz * r02;
  101051. py = dx * r10 + dy * r11 + dz * r12;
  101052. pz = dx * r20 + dy * r21 + dz * r22;
  101053. px = (dx = px) + c2x;
  101054. py = (dy = py) + c2y;
  101055. pz = (dz = pz) + c2z;
  101056. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  101057. if (pd <= 0) {
  101058. tx = px - pd * nx - c1x;
  101059. ty = py - pd * ny - c1y;
  101060. tz = pz - pd * nz - c1z;
  101061. len = tx * tx + ty * ty + tz * tz;
  101062. if (len > r1 * r1) {
  101063. len = r1 / OIMO.sqrt(len);
  101064. tx *= len;
  101065. ty *= len;
  101066. tz *= len;
  101067. }
  101068. px = c1x + tx;
  101069. py = c1y + ty;
  101070. pz = c1z + tz;
  101071. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  101072. }
  101073. px = dx * r00 + dy * r01 + dz * r02;
  101074. py = dx * r10 + dy * r11 + dz * r12;
  101075. pz = dx * r20 + dy * r21 + dz * r22;
  101076. px = (dx = px) + c2x;
  101077. py = (dy = py) + c2y;
  101078. pz = (dz = pz) + c2z;
  101079. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  101080. if (pd <= 0) {
  101081. tx = px - pd * nx - c1x;
  101082. ty = py - pd * ny - c1y;
  101083. tz = pz - pd * nz - c1z;
  101084. len = tx * tx + ty * ty + tz * tz;
  101085. if (len > r1 * r1) {
  101086. len = r1 / OIMO.sqrt(len);
  101087. tx *= len;
  101088. ty *= len;
  101089. tz *= len;
  101090. }
  101091. px = c1x + tx;
  101092. py = c1y + ty;
  101093. pz = c1z + tz;
  101094. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  101095. }
  101096. } else {
  101097. sx = tx;
  101098. sy = ty;
  101099. sz = tz;
  101100. depth1 = nx * (sx - c1x) + ny * (sy - c1y) + nz * (sz - c1z);
  101101. sx -= depth1 * nx;
  101102. sy -= depth1 * ny;
  101103. sz -= depth1 * nz;
  101104. if (dot > 0) {
  101105. ex = tx + n2x * h2 * 2;
  101106. ey = ty + n2y * h2 * 2;
  101107. ez = tz + n2z * h2 * 2;
  101108. } else {
  101109. ex = tx - n2x * h2 * 2;
  101110. ey = ty - n2y * h2 * 2;
  101111. ez = tz - n2z * h2 * 2;
  101112. }
  101113. depth2 = nx * (ex - c1x) + ny * (ey - c1y) + nz * (ez - c1z);
  101114. ex -= depth2 * nx;
  101115. ey -= depth2 * ny;
  101116. ez -= depth2 * nz;
  101117. dx = c1x - sx;
  101118. dy = c1y - sy;
  101119. dz = c1z - sz;
  101120. tx = ex - sx;
  101121. ty = ey - sy;
  101122. tz = ez - sz;
  101123. a = dx * dx + dy * dy + dz * dz;
  101124. b = dx * tx + dy * ty + dz * tz;
  101125. e = tx * tx + ty * ty + tz * tz;
  101126. f = b * b - e * (a - r1 * r1);
  101127. if (f < 0) break;
  101128. f = OIMO.sqrt(f);
  101129. t1 = (b + f) / e;
  101130. t2 = (b - f) / e;
  101131. if (t2 < t1) {
  101132. len = t1;
  101133. t1 = t2;
  101134. t2 = len;
  101135. }
  101136. if (t2 > 1) t2 = 1;
  101137. if (t1 < 0) t1 = 0;
  101138. tx = sx + (ex - sx) * t1;
  101139. ty = sy + (ey - sy) * t1;
  101140. tz = sz + (ez - sz) * t1;
  101141. ex = sx + (ex - sx) * t2;
  101142. ey = sy + (ey - sy) * t2;
  101143. ez = sz + (ez - sz) * t2;
  101144. sx = tx;
  101145. sy = ty;
  101146. sz = tz;
  101147. len = depth1 + (depth2 - depth1) * t1;
  101148. depth2 = depth1 + (depth2 - depth1) * t2;
  101149. depth1 = len;
  101150. if (depth1 < 0) manifold.addPoint(sx, sy, sz, nx, ny, nz, pd, false);
  101151. if (depth2 < 0) manifold.addPoint(ex, ey, ez, nx, ny, nz, pd, false);
  101152. }
  101153. break;
  101154. case 2:
  101155. if (right2) {
  101156. c2x = p2x - d2x;
  101157. c2y = p2y - d2y;
  101158. c2z = p2z - d2z;
  101159. nx = -n2x;
  101160. ny = -n2y;
  101161. nz = -n2z;
  101162. } else {
  101163. c2x = p2x + d2x;
  101164. c2y = p2y + d2y;
  101165. c2z = p2z + d2z;
  101166. nx = n2x;
  101167. ny = n2y;
  101168. nz = n2z;
  101169. }
  101170. dot = nx * n1x + ny * n1y + nz * n1z;
  101171. if (dot < 0) len = h1;
  101172. else len = -h1;
  101173. c1x = p1x + len * n1x;
  101174. c1y = p1y + len * n1y;
  101175. c1z = p1z + len * n1z;
  101176. if (dot1 >= 0.999999) {
  101177. tx = -ny;
  101178. ty = nz;
  101179. tz = nx;
  101180. } else {
  101181. tx = nx;
  101182. ty = ny;
  101183. tz = nz;
  101184. }
  101185. len = tx * n1x + ty * n1y + tz * n1z;
  101186. dx = len * n1x - tx;
  101187. dy = len * n1y - ty;
  101188. dz = len * n1z - tz;
  101189. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  101190. if (len == 0) break;
  101191. len = r1 / len;
  101192. dx *= len;
  101193. dy *= len;
  101194. dz *= len;
  101195. tx = c1x + dx;
  101196. ty = c1y + dy;
  101197. tz = c1z + dz;
  101198. if (dot < -0.96 || dot > 0.96) {
  101199. r00 = n1x * n1x * 1.5 - 0.5;
  101200. r01 = n1x * n1y * 1.5 - n1z * 0.866025403;
  101201. r02 = n1x * n1z * 1.5 + n1y * 0.866025403;
  101202. r10 = n1y * n1x * 1.5 + n1z * 0.866025403;
  101203. r11 = n1y * n1y * 1.5 - 0.5;
  101204. r12 = n1y * n1z * 1.5 - n1x * 0.866025403;
  101205. r20 = n1z * n1x * 1.5 - n1y * 0.866025403;
  101206. r21 = n1z * n1y * 1.5 + n1x * 0.866025403;
  101207. r22 = n1z * n1z * 1.5 - 0.5;
  101208. px = tx;
  101209. py = ty;
  101210. pz = tz;
  101211. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  101212. tx = px - pd * nx - c2x;
  101213. ty = py - pd * ny - c2y;
  101214. tz = pz - pd * nz - c2z;
  101215. len = tx * tx + ty * ty + tz * tz;
  101216. if (len > r2 * r2) {
  101217. len = r2 / OIMO.sqrt(len);
  101218. tx *= len;
  101219. ty *= len;
  101220. tz *= len;
  101221. }
  101222. px = c2x + tx;
  101223. py = c2y + ty;
  101224. pz = c2z + tz;
  101225. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  101226. px = dx * r00 + dy * r01 + dz * r02;
  101227. py = dx * r10 + dy * r11 + dz * r12;
  101228. pz = dx * r20 + dy * r21 + dz * r22;
  101229. px = (dx = px) + c1x;
  101230. py = (dy = py) + c1y;
  101231. pz = (dz = pz) + c1z;
  101232. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  101233. if (pd <= 0) {
  101234. tx = px - pd * nx - c2x;
  101235. ty = py - pd * ny - c2y;
  101236. tz = pz - pd * nz - c2z;
  101237. len = tx * tx + ty * ty + tz * tz;
  101238. if (len > r2 * r2) {
  101239. len = r2 / OIMO.sqrt(len);
  101240. tx *= len;
  101241. ty *= len;
  101242. tz *= len;
  101243. }
  101244. px = c2x + tx;
  101245. py = c2y + ty;
  101246. pz = c2z + tz;
  101247. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  101248. }
  101249. px = dx * r00 + dy * r01 + dz * r02;
  101250. py = dx * r10 + dy * r11 + dz * r12;
  101251. pz = dx * r20 + dy * r21 + dz * r22;
  101252. px = (dx = px) + c1x;
  101253. py = (dy = py) + c1y;
  101254. pz = (dz = pz) + c1z;
  101255. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  101256. if (pd <= 0) {
  101257. tx = px - pd * nx - c2x;
  101258. ty = py - pd * ny - c2y;
  101259. tz = pz - pd * nz - c2z;
  101260. len = tx * tx + ty * ty + tz * tz;
  101261. if (len > r2 * r2) {
  101262. len = r2 / OIMO.sqrt(len);
  101263. tx *= len;
  101264. ty *= len;
  101265. tz *= len;
  101266. }
  101267. px = c2x + tx;
  101268. py = c2y + ty;
  101269. pz = c2z + tz;
  101270. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  101271. }
  101272. } else {
  101273. sx = tx;
  101274. sy = ty;
  101275. sz = tz;
  101276. depth1 = nx * (sx - c2x) + ny * (sy - c2y) + nz * (sz - c2z);
  101277. sx -= depth1 * nx;
  101278. sy -= depth1 * ny;
  101279. sz -= depth1 * nz;
  101280. if (dot > 0) {
  101281. ex = tx + n1x * h1 * 2;
  101282. ey = ty + n1y * h1 * 2;
  101283. ez = tz + n1z * h1 * 2;
  101284. } else {
  101285. ex = tx - n1x * h1 * 2;
  101286. ey = ty - n1y * h1 * 2;
  101287. ez = tz - n1z * h1 * 2;
  101288. }
  101289. depth2 = nx * (ex - c2x) + ny * (ey - c2y) + nz * (ez - c2z);
  101290. ex -= depth2 * nx;
  101291. ey -= depth2 * ny;
  101292. ez -= depth2 * nz;
  101293. dx = c2x - sx;
  101294. dy = c2y - sy;
  101295. dz = c2z - sz;
  101296. tx = ex - sx;
  101297. ty = ey - sy;
  101298. tz = ez - sz;
  101299. a = dx * dx + dy * dy + dz * dz;
  101300. b = dx * tx + dy * ty + dz * tz;
  101301. e = tx * tx + ty * ty + tz * tz;
  101302. f = b * b - e * (a - r2 * r2);
  101303. if (f < 0) break;
  101304. f = OIMO.sqrt(f);
  101305. t1 = (b + f) / e;
  101306. t2 = (b - f) / e;
  101307. if (t2 < t1) {
  101308. len = t1;
  101309. t1 = t2;
  101310. t2 = len;
  101311. }
  101312. if (t2 > 1) t2 = 1;
  101313. if (t1 < 0) t1 = 0;
  101314. tx = sx + (ex - sx) * t1;
  101315. ty = sy + (ey - sy) * t1;
  101316. tz = sz + (ez - sz) * t1;
  101317. ex = sx + (ex - sx) * t2;
  101318. ey = sy + (ey - sy) * t2;
  101319. ez = sz + (ez - sz) * t2;
  101320. sx = tx;
  101321. sy = ty;
  101322. sz = tz;
  101323. len = depth1 + (depth2 - depth1) * t1;
  101324. depth2 = depth1 + (depth2 - depth1) * t2;
  101325. depth1 = len;
  101326. if (depth1 < 0) {
  101327. manifold.addPoint(sx, sy, sz, -nx, -ny, -nz, depth1, false);
  101328. }
  101329. if (depth2 < 0) {
  101330. manifold.addPoint(ex, ey, ez, -nx, -ny, -nz, depth2, false);
  101331. }
  101332. }
  101333. break;
  101334. }
  101335. };
  101336. OIMO.SphereCylinderCollisionDetector = function (flip) {
  101337. OIMO.CollisionDetector.call(this);
  101338. this.flip = flip;
  101339. };
  101340. OIMO.SphereCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  101341. OIMO.SphereCylinderCollisionDetector.prototype.constructor = OIMO.SphereCylinderCollisionDetector;
  101342. OIMO.SphereCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  101343. var s;
  101344. var c;
  101345. if (this.flip) {
  101346. s = shape2;
  101347. c = shape1;
  101348. } else {
  101349. s = shape1;
  101350. c = shape2;
  101351. }
  101352. var ps = s.position;
  101353. var psx = ps.x;
  101354. var psy = ps.y;
  101355. var psz = ps.z;
  101356. var pc = c.position;
  101357. var pcx = pc.x;
  101358. var pcy = pc.y;
  101359. var pcz = pc.z;
  101360. var dirx = c.normalDirection.x;
  101361. var diry = c.normalDirection.y;
  101362. var dirz = c.normalDirection.z;
  101363. var rads = s.radius;
  101364. var radc = c.radius;
  101365. var rad2 = rads + radc;
  101366. var halfh = c.halfHeight;
  101367. var dx = psx - pcx;
  101368. var dy = psy - pcy;
  101369. var dz = psz - pcz;
  101370. var dot = dx * dirx + dy * diry + dz * dirz;
  101371. if (dot < -halfh - rads || dot > halfh + rads) return;
  101372. var cx = pcx + dot * dirx;
  101373. var cy = pcy + dot * diry;
  101374. var cz = pcz + dot * dirz;
  101375. var d2x = psx - cx;
  101376. var d2y = psy - cy;
  101377. var d2z = psz - cz;
  101378. var len = d2x * d2x + d2y * d2y + d2z * d2z;
  101379. if (len > rad2 * rad2) return;
  101380. if (len > radc * radc) {
  101381. len = radc / OIMO.sqrt(len);
  101382. d2x *= len;
  101383. d2y *= len;
  101384. d2z *= len;
  101385. }
  101386. if (dot < -halfh) dot = -halfh;
  101387. else if (dot > halfh) dot = halfh;
  101388. cx = pcx + dot * dirx + d2x;
  101389. cy = pcy + dot * diry + d2y;
  101390. cz = pcz + dot * dirz + d2z;
  101391. dx = cx - psx;
  101392. dy = cy - psy;
  101393. dz = cz - psz;
  101394. len = dx * dx + dy * dy + dz * dz;
  101395. var invLen;
  101396. if (len > 0 && len < rads * rads) {
  101397. len = OIMO.sqrt(len);
  101398. invLen = 1 / len;
  101399. dx *= invLen;
  101400. dy *= invLen;
  101401. dz *= invLen;
  101402. ///result.addContactInfo(psx+dx*rads,psy+dy*rads,psz+dz*rads,dx,dy,dz,len-rads,s,c,0,0,false);
  101403. manifold.addPoint(psx + dx * rads, psy + dy * rads, psz + dz * rads, dx, dy, dz, len - rads, this.flip);
  101404. }
  101405. };
  101406. /**
  101407. * Class for checking collisions between 2 tetras,
  101408. * a shape that is made with 4 vertices and 4 faces
  101409. * arranged in triangles. With this algorigthm, soft
  101410. * body physics are possible and easier to implement.
  101411. * @author xprogram
  101412. */
  101413. OIMO.TetraTetraCollisionDetector = function () {
  101414. OIMO.CollisionDetector.call(this);
  101415. };
  101416. OIMO.TetraTetraCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  101417. OIMO.TetraTetraCollisionDetector.prototype.constructor = OIMO.TetraTetraCollisionDetector;
  101418. OIMO.TetraTetraCollisionDetector.prototype.detectCollision = function (tet1, tet2, manifold) {
  101419. /*
  101420. * What we are doing:
  101421. * Each tetra is represented by four 3D triangles. The only
  101422. * quick way of finding if another tetra is within the other
  101423. * tetra is to see if a single vertex is within the triangles
  101424. * of the other tetra. So, for example, a tetra is represented
  101425. * by points B, C, D and E with triangles BCD, BCE, DCE and BDE.
  101426. * There is another tetra with a vertex A which was detected for
  101427. * collision by the broadphase. Now, if the point A is between ALL
  101428. * triangles of the other tetra (BCD, BCE, etc.) then the collision
  101429. * is valid and we can pass point A to the manifold. Since the only
  101430. * points on the tetra are the 4 vertices, collision detection is
  101431. * not so complex. However, it can be time-consuming because we
  101432. * need to split the 3D triangles into three 2D triangles each for
  101433. * collision detection.
  101434. */
  101435. var i, j, vec, fs1 = tet1.faces, vs1 = tet1.verts, fs2 = tet2.faces, vs2 = tet2.verts;
  101436. var j1, j2, j3, ts = 0; // Triangle vertices `j1`, `j2` and `j3`
  101437. // fs is undeclared
  101438. var fs = fs1;
  101439. for (i = 0; i < 4; i++) {
  101440. vec = vs1[i];
  101441. for (j = 0; j < 4; j++) {
  101442. j1 = vs2[fs[i].a];
  101443. j2 = vs2[fs[i].b];
  101444. j3 = vs2[fs[i].c];
  101445. if (
  101446. tricheck(pt(vec.x, vec.y), pt(j1.x, j1.y), pt(j2.x, j2.y), pt(j3.x, j3.y)) &&
  101447. tricheck(pt(vec.x, vec.z), pt(j1.x, j1.z), pt(j2.x, j2.z), pt(j3.x, j3.z)) &&
  101448. tricheck(pt(vec.z, vec.y), pt(j1.z, j1.y), pt(j2.z, j2.y), pt(j3.z, j3.y))
  101449. )
  101450. ts++;
  101451. if (ts === 4) // Only add point if it is inside all 4 triangles
  101452. manifold.addPoint(vec);
  101453. }
  101454. }
  101455. };
  101456. // Taken from: http://jsfiddle.net/PerroAZUL/zdaY8/1/
  101457. function tricheck(p, p0, p1, p2) {
  101458. var A = 0.5 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  101459. var sg = A < 0 ? -1 : 1;
  101460. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sg;
  101461. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sg;
  101462. return s > 0 && t > 0 && (s + t) < 2 * A * sg;
  101463. }
  101464. function pt(x, y) { return { x: x, y: y }; }
  101465. /**
  101466. * An axis-aligned bounding box.
  101467. * @author saharan
  101468. * @author lo-th
  101469. */
  101470. OIMO.AABB = function (minX, maxX, minY, maxY, minZ, maxZ) {
  101471. this.elements = new OIMO_ARRAY_TYPE(6);
  101472. var te = this.elements;
  101473. te[0] = minX || 0; te[1] = minY || 0; te[2] = minZ || 0;
  101474. te[3] = maxX || 0; te[4] = maxY || 0; te[5] = maxZ || 0;
  101475. };
  101476. OIMO.AABB.prototype = {
  101477. constructor: OIMO.AABB,
  101478. set: function (minX, maxX, minY, maxY, minZ, maxZ) {
  101479. var te = this.elements;
  101480. te[0] = minX; te[3] = maxX;
  101481. te[1] = minY; te[4] = maxY;
  101482. te[2] = minZ; te[5] = maxZ;
  101483. return this;
  101484. },
  101485. intersectTest: function (aabb) {
  101486. var te = this.elements;
  101487. var ue = aabb.elements;
  101488. 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];
  101489. },
  101490. intersectTestTwo: function (aabb) {
  101491. var te = this.elements;
  101492. var ue = aabb.elements;
  101493. 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];
  101494. },
  101495. clone: function () {
  101496. return new this.constructor().fromArray(this.elements);
  101497. },
  101498. copy: function (aabb, margin) {
  101499. var m = margin || 0;
  101500. var me = aabb.elements;
  101501. this.set(me[0] - m, me[3] + m, me[1] - m, me[4] + m, me[2] - m, me[5] + m);
  101502. return this;
  101503. },
  101504. fromArray: function (array) {
  101505. this.elements.set(array);
  101506. return this;
  101507. },
  101508. // Set this AABB to the combined AABB of aabb1 and aabb2.
  101509. combine: function (aabb1, aabb2) {
  101510. var a = aabb1.elements;
  101511. var b = aabb2.elements;
  101512. var te = this.elements;
  101513. te[0] = a[0] < b[0] ? a[0] : b[0];
  101514. te[1] = a[1] < b[1] ? a[1] : b[1];
  101515. te[2] = a[2] < b[2] ? a[2] : b[2];
  101516. te[3] = a[3] > b[3] ? a[3] : b[3];
  101517. te[4] = a[4] > b[4] ? a[4] : b[4];
  101518. te[5] = a[5] > b[5] ? a[5] : b[5];
  101519. return this;
  101520. },
  101521. // Get the surface area.
  101522. surfaceArea: function () {
  101523. var te = this.elements;
  101524. var a = te[3] - te[0];
  101525. var h = te[4] - te[1];
  101526. var d = te[5] - te[2];
  101527. return 2 * (a * (h + d) + h * d);
  101528. },
  101529. // Get whether the AABB intersects with the point or not.
  101530. intersectsWithPoint: function (x, y, z) {
  101531. var te = this.elements;
  101532. return x >= te[0] && x <= te[3] && y >= te[1] && y <= te[4] && z >= te[2] && z <= te[5];
  101533. },
  101534. /**
  101535. * Set the AABB from an array
  101536. * of vertices. From THREE.
  101537. * @author mrdoob
  101538. * @author xprogram
  101539. */
  101540. setFromPoints: function (arr) {
  101541. this.makeEmpty();
  101542. for (var i = 0; i < arr.length; i++) {
  101543. this.expandByPoint(arr[i]);
  101544. }
  101545. },
  101546. makeEmpty: function () {
  101547. this.set(-Infinity, -Infinity, -Infinity, Infinity, Infinity, Infinity);
  101548. },
  101549. expandByPoint: function (pt) {
  101550. var te = this.elements;
  101551. this.set(
  101552. OIMO.min(te[0], pt.x), OIMO.min(te[1], pt.y), OIMO.min(te[2], pt.z),
  101553. OIMO.max(te[3], pt.x), OIMO.max(te[4], pt.y), OIMO.max(te[5], pt.z)
  101554. );
  101555. }
  101556. };
  101557. /**
  101558. * A proxy is used for broad-phase collecting pairs that can be colliding.
  101559. */
  101560. OIMO.Proxy = function (shape) {
  101561. // The parent shape.
  101562. this.shape = shape;
  101563. // The axis-aligned bounding box.
  101564. this.aabb = shape.aabb;
  101565. };
  101566. OIMO.Proxy.prototype = {
  101567. constructor: OIMO.Proxy,
  101568. // Update the proxy.
  101569. update: function () {
  101570. OIMO.Error("Proxy", "Inheritance error.");
  101571. }
  101572. };
  101573. /**
  101574. * A basic implementation of proxies.
  101575. * @author saharan
  101576. */
  101577. OIMO.BasicProxy = function (shape) {
  101578. OIMO.Proxy.call(this, shape);
  101579. this.id = OIMO.proxyID++;
  101580. };
  101581. OIMO.BasicProxy.prototype = Object.create(OIMO.Proxy.prototype);
  101582. OIMO.BasicProxy.prototype.constructor = OIMO.BasicProxy;
  101583. OIMO.BasicProxy.prototype.update = function () {
  101584. };
  101585. /**
  101586. * The broad-phase is used for collecting all possible pairs for collision.
  101587. */
  101588. OIMO.BroadPhase = function () {
  101589. this.types = OIMO.BR_NULL;
  101590. this.numPairChecks = 0;
  101591. this.numPairs = 0;
  101592. this.pairs = [];
  101593. };
  101594. OIMO.BroadPhase.prototype = {
  101595. constructor: OIMO.BroadPhase,
  101596. /**
  101597. * Create a new proxy.
  101598. * @param shape
  101599. * @return
  101600. */
  101601. createProxy: function (shape) {
  101602. OIMO.Error("BroadPhase", "Inheritance error.");
  101603. },
  101604. /**
  101605. * Add the proxy into the broad-phase.
  101606. * @param proxy
  101607. */
  101608. addProxy: function (proxy) {
  101609. OIMO.Error("BroadPhase", "Inheritance error.");
  101610. },
  101611. /**
  101612. * Remove the proxy from the broad-phase.
  101613. * @param proxy
  101614. */
  101615. removeProxy: function (proxy) {
  101616. OIMO.Error("BroadPhase", "Inheritance error.");
  101617. },
  101618. /**
  101619. * Returns whether the pair is available or not.
  101620. * @param s1
  101621. * @param s2
  101622. * @return
  101623. */
  101624. isAvailablePair: function (s1, s2) {
  101625. var b1 = s1.parent;
  101626. var b2 = s2.parent;
  101627. if (b1 == b2 || // same parents
  101628. (!b1.isDynamic && !b2.isDynamic) || // static or kinematic object
  101629. (s1.belongsTo & s2.collidesWith) == 0 ||
  101630. (s2.belongsTo & s1.collidesWith) == 0 // collision filtering
  101631. ) { return false; }
  101632. var js;
  101633. if (b1.numJoints < b2.numJoints) js = b1.jointLink;
  101634. else js = b2.jointLink;
  101635. while (js !== null) {
  101636. var joint = js.joint;
  101637. if (!joint.allowCollision && ((joint.body1 == b1 && joint.body2 == b2) || (joint.body1 == b2 && joint.body2 == b1))) { return false; }
  101638. js = js.next;
  101639. }
  101640. return true;
  101641. },
  101642. // Detect overlapping pairs.
  101643. detectPairs: function () {
  101644. // clear old
  101645. this.pairs = [];
  101646. this.numPairs = 0;
  101647. this.numPairChecks = 0;
  101648. this.collectPairs();
  101649. },
  101650. collectPairs: function () {
  101651. OIMO.Error("BroadPhase", "Inheritance error.");
  101652. },
  101653. addPair: function (s1, s2) {
  101654. var pair = new OIMO.Pair(s1, s2);
  101655. this.pairs.push(pair);
  101656. this.numPairs++;
  101657. }
  101658. };
  101659. /**
  101660. * A broad-phase algorithm with brute-force search.
  101661. * This always checks for all possible pairs.
  101662. */
  101663. OIMO.BruteForceBroadPhase = function () {
  101664. OIMO.BroadPhase.call(this);
  101665. this.types = OIMO.BR_BRUTE_FORCE;;
  101666. //this.numProxies=0;
  101667. ///this.maxProxies = 256;
  101668. this.proxies = [];
  101669. //this.proxies.length = 256;
  101670. };
  101671. OIMO.BruteForceBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  101672. OIMO.BruteForceBroadPhase.prototype.constructor = OIMO.BruteForceBroadPhase;
  101673. OIMO.BruteForceBroadPhase.prototype.createProxy = function (shape) {
  101674. return new OIMO.BasicProxy(shape);
  101675. };
  101676. OIMO.BruteForceBroadPhase.prototype.addProxy = function (proxy) {
  101677. /*if(this.numProxies==this.maxProxies){
  101678. //this.maxProxies<<=1;
  101679. this.maxProxies*=2;
  101680. var newProxies=[];
  101681. newProxies.length = this.maxProxies;
  101682. var i = this.numProxies;
  101683. while(i--){
  101684. //for(var i=0, l=this.numProxies;i<l;i++){
  101685. newProxies[i]=this.proxies[i];
  101686. }
  101687. this.proxies=newProxies;
  101688. }*/
  101689. //this.proxies[this.numProxies++] = proxy;
  101690. this.proxies.push(proxy);
  101691. //this.numProxies++;
  101692. };
  101693. OIMO.BruteForceBroadPhase.prototype.removeProxy = function (proxy) {
  101694. var n = this.proxies.indexOf(proxy);
  101695. if (n > -1) {
  101696. this.proxies.splice(n, 1);
  101697. //this.numProxies--;
  101698. }
  101699. /*var i = this.numProxies;
  101700. while(i--){
  101701. //for(var i=0, l=this.numProxies;i<l;i++){
  101702. if(this.proxies[i] == proxy){
  101703. this.proxies[i] = this.proxies[--this.numProxies];
  101704. this.proxies[this.numProxies] = null;
  101705. return;
  101706. }
  101707. }*/
  101708. };
  101709. OIMO.BruteForceBroadPhase.prototype.collectPairs = function () {
  101710. var i = 0, j, p1, p2;
  101711. var px = this.proxies;
  101712. var l = px.length;//this.numProxies;
  101713. //var ar1 = [];
  101714. //var ar2 = [];
  101715. //for( i = px.length ; i-- ; ar1[ i ] = px[ i ] ){};
  101716. //for( i = px.length ; i-- ; ar2[ i ] = px[ i ] ){};
  101717. //var ar1 = JSON.parse(JSON.stringify(this.proxies))
  101718. //var ar2 = JSON.parse(JSON.stringify(this.proxies))
  101719. this.numPairChecks = l * (l - 1) >> 1;
  101720. //this.numPairChecks=this.numProxies*(this.numProxies-1)*0.5;
  101721. while (i < l) {
  101722. p1 = px[i++];
  101723. j = i + 1;
  101724. while (j < l) {
  101725. p2 = px[j++];
  101726. if (p1.aabb.intersectTest(p2.aabb) || !this.isAvailablePair(p1.shape, p2.shape)) continue;
  101727. this.addPair(p1.shape, p2.shape);
  101728. }
  101729. }
  101730. };
  101731. /**
  101732. * A pair of shapes that may collide.
  101733. * @author saharan
  101734. */
  101735. OIMO.Pair = function (s1, s2) {
  101736. // The first shape.
  101737. this.shape1 = s1 || null;
  101738. // The second shape.
  101739. this.shape2 = s2 || null;
  101740. };
  101741. /**
  101742. * A projection axis for sweep and prune broad-phase.
  101743. * @author saharan
  101744. */
  101745. OIMO.SAPAxis = function () {
  101746. this.numElements = 0;
  101747. this.bufferSize = 256;
  101748. this.elements = [];
  101749. this.elements.length = this.bufferSize;
  101750. this.stack = new OIMO_ARRAY_TYPE(64);
  101751. };
  101752. OIMO.SAPAxis.prototype = {
  101753. constructor: OIMO.SAPAxis,
  101754. addElements: function (min, max) {
  101755. if (this.numElements + 2 >= this.bufferSize) {
  101756. //this.bufferSize<<=1;
  101757. this.bufferSize *= 2;
  101758. var newElements = [];
  101759. var i = this.numElements;
  101760. while (i--) {
  101761. //for(var i=0, l=this.numElements; i<l; i++){
  101762. newElements[i] = this.elements[i];
  101763. }
  101764. }
  101765. this.elements[this.numElements++] = min;
  101766. this.elements[this.numElements++] = max;
  101767. },
  101768. removeElements: function (min, max) {
  101769. var minIndex = -1;
  101770. var maxIndex = -1;
  101771. for (var i = 0, l = this.numElements; i < l; i++) {
  101772. var e = this.elements[i];
  101773. if (e == min || e == max) {
  101774. if (minIndex == -1) {
  101775. minIndex = i;
  101776. } else {
  101777. maxIndex = i;
  101778. break;
  101779. }
  101780. }
  101781. }
  101782. for (i = minIndex + 1, l = maxIndex; i < l; i++) {
  101783. this.elements[i - 1] = this.elements[i];
  101784. }
  101785. for (i = maxIndex + 1, l = this.numElements; i < l; i++) {
  101786. this.elements[i - 2] = this.elements[i];
  101787. }
  101788. this.elements[--this.numElements] = null;
  101789. this.elements[--this.numElements] = null;
  101790. },
  101791. sort: function () {
  101792. var count = 0;
  101793. var threshold = 1;
  101794. while ((this.numElements >> threshold) != 0) threshold++;
  101795. threshold = threshold * this.numElements >> 2;
  101796. count = 0;
  101797. var giveup = false;
  101798. var elements = this.elements;
  101799. for (var i = 1, l = this.numElements; i < l; i++) { // try insertion sort
  101800. var tmp = elements[i];
  101801. var pivot = tmp.value;
  101802. var tmp2 = elements[i - 1];
  101803. if (tmp2.value > pivot) {
  101804. var j = i;
  101805. do {
  101806. elements[j] = tmp2;
  101807. if (--j == 0) break;
  101808. tmp2 = elements[j - 1];
  101809. } while (tmp2.value > pivot);
  101810. elements[j] = tmp;
  101811. count += i - j;
  101812. if (count > threshold) {
  101813. giveup = true; // stop and use quick sort
  101814. break;
  101815. }
  101816. }
  101817. }
  101818. if (!giveup) return;
  101819. count = 2; var stack = this.stack;
  101820. stack[0] = 0;
  101821. stack[1] = this.numElements - 1;
  101822. while (count > 0) {
  101823. var right = stack[--count];
  101824. var left = stack[--count];
  101825. var diff = right - left;
  101826. if (diff > 16) { // quick sort
  101827. //var mid=left+(diff>>1);
  101828. var mid = left + (OIMO.floor(diff * 0.5));
  101829. tmp = elements[mid];
  101830. elements[mid] = elements[right];
  101831. elements[right] = tmp;
  101832. pivot = tmp.value;
  101833. i = left - 1;
  101834. j = right;
  101835. while (true) {
  101836. var ei;
  101837. var ej;
  101838. do { ei = elements[++i]; } while (ei.value < pivot);
  101839. do { ej = elements[--j]; } while (pivot < ej.value && j != left);
  101840. if (i >= j) break;
  101841. elements[i] = ej;
  101842. elements[j] = ei;
  101843. }
  101844. elements[right] = elements[i];
  101845. elements[i] = tmp;
  101846. if (i - left > right - i) {
  101847. stack[count++] = left;
  101848. stack[count++] = i - 1;
  101849. stack[count++] = i + 1;
  101850. stack[count++] = right;
  101851. } else {
  101852. stack[count++] = i + 1;
  101853. stack[count++] = right;
  101854. stack[count++] = left;
  101855. stack[count++] = i - 1;
  101856. }
  101857. } else {
  101858. for (i = left + 1; i <= right; i++) {
  101859. tmp = elements[i];
  101860. pivot = tmp.value;
  101861. tmp2 = elements[i - 1];
  101862. if (tmp2.value > pivot) {
  101863. j = i;
  101864. do {
  101865. elements[j] = tmp2;
  101866. if (--j == 0) break;
  101867. tmp2 = elements[j - 1];
  101868. } while (tmp2.value > pivot);
  101869. elements[j] = tmp;
  101870. }
  101871. }
  101872. }
  101873. }
  101874. },
  101875. calculateTestCount: function () {
  101876. var num = 1;
  101877. var sum = 0;
  101878. for (var i = 1, l = this.numElements; i < l; i++) {
  101879. if (this.elements[i].max) {
  101880. num--;
  101881. } else {
  101882. sum += num;
  101883. num++;
  101884. }
  101885. }
  101886. return sum;
  101887. }
  101888. }
  101889. /**
  101890. * A broad-phase collision detection algorithm using sweep and prune.
  101891. * @author saharan
  101892. * @author lo-th
  101893. */
  101894. OIMO.SAPBroadPhase = function () {
  101895. OIMO.BroadPhase.call(this);
  101896. this.types = OIMO.BR_SWEEP_AND_PRUNE;
  101897. this.numElementsD = 0;
  101898. this.numElementsS = 0;
  101899. // dynamic proxies
  101900. this.axesD = [
  101901. new OIMO.SAPAxis(),
  101902. new OIMO.SAPAxis(),
  101903. new OIMO.SAPAxis()
  101904. ];
  101905. // static or sleeping proxies
  101906. this.axesS = [
  101907. new OIMO.SAPAxis(),
  101908. new OIMO.SAPAxis(),
  101909. new OIMO.SAPAxis()
  101910. ];
  101911. this.index1 = 0;
  101912. this.index2 = 1;
  101913. };
  101914. OIMO.SAPBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  101915. OIMO.SAPBroadPhase.prototype.constructor = OIMO.SAPBroadPhase;
  101916. OIMO.SAPBroadPhase.prototype.createProxy = function (shape) {
  101917. return new OIMO.SAPProxy(this, shape);
  101918. };
  101919. OIMO.SAPBroadPhase.prototype.addProxy = function (proxy) {
  101920. var p = proxy;
  101921. if (p.isDynamic()) {
  101922. this.axesD[0].addElements(p.min[0], p.max[0]);
  101923. this.axesD[1].addElements(p.min[1], p.max[1]);
  101924. this.axesD[2].addElements(p.min[2], p.max[2]);
  101925. p.belongsTo = 1;
  101926. this.numElementsD += 2;
  101927. } else {
  101928. this.axesS[0].addElements(p.min[0], p.max[0]);
  101929. this.axesS[1].addElements(p.min[1], p.max[1]);
  101930. this.axesS[2].addElements(p.min[2], p.max[2]);
  101931. p.belongsTo = 2;
  101932. this.numElementsS += 2;
  101933. }
  101934. };
  101935. OIMO.SAPBroadPhase.prototype.removeProxy = function (proxy) {
  101936. var p = proxy;
  101937. if (p.belongsTo == 0) return;
  101938. /*else if ( p.belongsTo == 1 ) {
  101939. this.axesD[0].removeElements( p.min[0], p.max[0] );
  101940. this.axesD[1].removeElements( p.min[1], p.max[1] );
  101941. this.axesD[2].removeElements( p.min[2], p.max[2] );
  101942. this.numElementsD -= 2;
  101943. } else if ( p.belongsTo == 2 ) {
  101944. this.axesS[0].removeElements( p.min[0], p.max[0] );
  101945. this.axesS[1].removeElements( p.min[1], p.max[1] );
  101946. this.axesS[2].removeElements( p.min[2], p.max[2] );
  101947. this.numElementsS -= 2;
  101948. }*/
  101949. switch (p.belongsTo) {
  101950. case 1:
  101951. this.axesD[0].removeElements(p.min[0], p.max[0]);
  101952. this.axesD[1].removeElements(p.min[1], p.max[1]);
  101953. this.axesD[2].removeElements(p.min[2], p.max[2]);
  101954. this.numElementsD -= 2;
  101955. break;
  101956. case 2:
  101957. this.axesS[0].removeElements(p.min[0], p.max[0]);
  101958. this.axesS[1].removeElements(p.min[1], p.max[1]);
  101959. this.axesS[2].removeElements(p.min[2], p.max[2]);
  101960. this.numElementsS -= 2;
  101961. break;
  101962. }
  101963. p.belongsTo = 0;
  101964. };
  101965. OIMO.SAPBroadPhase.prototype.collectPairs = function () {
  101966. if (this.numElementsD == 0) return;
  101967. var axis1 = this.axesD[this.index1];
  101968. var axis2 = this.axesD[this.index2];
  101969. axis1.sort();
  101970. axis2.sort();
  101971. var count1 = axis1.calculateTestCount();
  101972. var count2 = axis2.calculateTestCount();
  101973. var elementsD;
  101974. var elementsS;
  101975. if (count1 <= count2) {// select the best axis
  101976. axis2 = this.axesS[this.index1];
  101977. axis2.sort();
  101978. elementsD = axis1.elements;
  101979. elementsS = axis2.elements;
  101980. } else {
  101981. axis1 = this.axesS[this.index2];
  101982. axis1.sort();
  101983. elementsD = axis2.elements;
  101984. elementsS = axis1.elements;
  101985. this.index1 ^= this.index2;
  101986. this.index2 ^= this.index1;
  101987. this.index1 ^= this.index2;
  101988. }
  101989. var activeD;
  101990. var activeS;
  101991. var p = 0;
  101992. var q = 0;
  101993. while (p < this.numElementsD) {
  101994. var e1;
  101995. var dyn;
  101996. if (q == this.numElementsS) {
  101997. e1 = elementsD[p];
  101998. dyn = true;
  101999. p++;
  102000. } else {
  102001. var d = elementsD[p];
  102002. var s = elementsS[q];
  102003. if (d.value < s.value) {
  102004. e1 = d;
  102005. dyn = true;
  102006. p++;
  102007. } else {
  102008. e1 = s;
  102009. dyn = false;
  102010. q++;
  102011. }
  102012. }
  102013. if (!e1.max) {
  102014. var s1 = e1.proxy.shape;
  102015. var min1 = e1.min1.value;
  102016. var max1 = e1.max1.value;
  102017. var min2 = e1.min2.value;
  102018. var max2 = e1.max2.value;
  102019. for (var e2 = activeD; e2 != null; e2 = e2.pair) {// test for dynamic
  102020. var s2 = e2.proxy.shape;
  102021. this.numPairChecks++;
  102022. if (min1 > e2.max1.value || max1 < e2.min1.value || min2 > e2.max2.value || max2 < e2.min2.value || !this.isAvailablePair(s1, s2)) continue;
  102023. this.addPair(s1, s2);
  102024. }
  102025. if (dyn) {
  102026. for (e2 = activeS; e2 != null; e2 = e2.pair) {// test for static
  102027. s2 = e2.proxy.shape;
  102028. this.numPairChecks++;
  102029. if (min1 > e2.max1.value || max1 < e2.min1.value || min2 > e2.max2.value || max2 < e2.min2.value || !this.isAvailablePair(s1, s2)) continue;
  102030. this.addPair(s1, s2);
  102031. }
  102032. e1.pair = activeD;
  102033. activeD = e1;
  102034. } else {
  102035. e1.pair = activeS;
  102036. activeS = e1;
  102037. }
  102038. } else {
  102039. var min = e1.pair;
  102040. if (dyn) {
  102041. if (min == activeD) {
  102042. activeD = activeD.pair;
  102043. continue;
  102044. } else {
  102045. e1 = activeD;
  102046. }
  102047. } else {
  102048. if (min == activeS) {
  102049. activeS = activeS.pair;
  102050. continue;
  102051. } else {
  102052. e1 = activeS;
  102053. }
  102054. }
  102055. do {
  102056. e2 = e1.pair;
  102057. if (e2 == min) {
  102058. e1.pair = e2.pair;
  102059. break;
  102060. }
  102061. e1 = e2;
  102062. } while (e1 != null);
  102063. }
  102064. }
  102065. this.index2 = (this.index1 | this.index2) ^ 3;
  102066. };
  102067. /**
  102068. * An element of proxies.
  102069. * @author saharan
  102070. */
  102071. OIMO.SAPElement = function (proxy, max) {
  102072. // The parent proxy
  102073. this.proxy = proxy;
  102074. // The pair element.
  102075. this.pair = null;
  102076. // The minimum element on other axis.
  102077. this.min1 = null;
  102078. // The maximum element on other axis.
  102079. this.max1 = null;
  102080. // The minimum element on other axis.
  102081. this.min2 = null;
  102082. // The maximum element on other axis.
  102083. this.max2 = null;
  102084. // Whether the element has maximum value or not.
  102085. this.max = max;
  102086. // The value of the element.
  102087. this.value = 0;
  102088. };
  102089. /**
  102090. * A proxy for sweep and prune broad-phase.
  102091. * @author saharan
  102092. * @author lo-th
  102093. */
  102094. OIMO.SAPProxy = function (sap, shape) {
  102095. OIMO.Proxy.call(this, shape);
  102096. // Type of the axis to which the proxy belongs to. [0:none, 1:dynamic, 2:static]
  102097. this.belongsTo = 0;
  102098. // The maximum elements on each axis.
  102099. this.max = [];
  102100. // The minimum elements on each axis.
  102101. this.min = [];
  102102. this.sap = sap;
  102103. this.min[0] = new OIMO.SAPElement(this, false);
  102104. this.max[0] = new OIMO.SAPElement(this, true);
  102105. this.min[1] = new OIMO.SAPElement(this, false);
  102106. this.max[1] = new OIMO.SAPElement(this, true);
  102107. this.min[2] = new OIMO.SAPElement(this, false);
  102108. this.max[2] = new OIMO.SAPElement(this, true);
  102109. this.max[0].pair = this.min[0];
  102110. this.max[1].pair = this.min[1];
  102111. this.max[2].pair = this.min[2];
  102112. this.min[0].min1 = this.min[1];
  102113. this.min[0].max1 = this.max[1];
  102114. this.min[0].min2 = this.min[2];
  102115. this.min[0].max2 = this.max[2];
  102116. this.min[1].min1 = this.min[0];
  102117. this.min[1].max1 = this.max[0];
  102118. this.min[1].min2 = this.min[2];
  102119. this.min[1].max2 = this.max[2];
  102120. this.min[2].min1 = this.min[0];
  102121. this.min[2].max1 = this.max[0];
  102122. this.min[2].min2 = this.min[1];
  102123. this.min[2].max2 = this.max[1];
  102124. };
  102125. OIMO.SAPProxy.prototype = Object.create(OIMO.Proxy.prototype);
  102126. OIMO.SAPProxy.prototype.constructor = OIMO.SAPProxy;
  102127. // Returns whether the proxy is dynamic or not.
  102128. OIMO.SAPProxy.prototype.isDynamic = function () {
  102129. var body = this.shape.parent;
  102130. return body.isDynamic && !body.sleeping;
  102131. };
  102132. OIMO.SAPProxy.prototype.update = function () {
  102133. var te = this.aabb.elements;
  102134. this.min[0].value = te[0];
  102135. this.min[1].value = te[1];
  102136. this.min[2].value = te[2];
  102137. this.max[0].value = te[3];
  102138. this.max[1].value = te[4];
  102139. this.max[2].value = te[5];
  102140. if (this.belongsTo == 1 && !this.isDynamic() || this.belongsTo == 2 && this.isDynamic()) {
  102141. this.sap.removeProxy(this);
  102142. this.sap.addProxy(this);
  102143. }
  102144. };
  102145. /**
  102146. * A dynamic bounding volume tree for the broad-phase algorithm.
  102147. * @author saharan
  102148. * @author lo-th
  102149. */
  102150. OIMO.DBVT = function () {
  102151. // The root of the tree.
  102152. this.root = null;
  102153. this.freeNodes = [];
  102154. this.freeNodes.length = 16384;
  102155. this.numFreeNodes = 0;
  102156. this.aabb = new OIMO.AABB();
  102157. };
  102158. OIMO.DBVT.prototype = {
  102159. constructor: OIMO.DBVT,
  102160. /**
  102161. * Move a leaf.
  102162. * @param leaf
  102163. */
  102164. moveLeaf: function (leaf) {
  102165. this.deleteLeaf(leaf);
  102166. this.insertLeaf(leaf);
  102167. },
  102168. /**
  102169. * Insert a leaf to the tree.
  102170. * @param node
  102171. */
  102172. insertLeaf: function (leaf) {
  102173. if (this.root == null) {
  102174. this.root = leaf;
  102175. return;
  102176. }
  102177. var lb = leaf.aabb;
  102178. var sibling = this.root;
  102179. var oldArea;
  102180. var newArea;
  102181. while (sibling.proxy == null) { // descend the node to search the best pair
  102182. var c1 = sibling.child1;
  102183. var c2 = sibling.child2;
  102184. var b = sibling.aabb;
  102185. var c1b = c1.aabb;
  102186. var c2b = c2.aabb;
  102187. oldArea = b.surfaceArea();
  102188. this.aabb.combine(lb, b);
  102189. newArea = this.aabb.surfaceArea();
  102190. var creatingCost = newArea * 2;
  102191. var incrementalCost = (newArea - oldArea) * 2; // cost of creating a new pair with the node
  102192. var discendingCost1 = incrementalCost;
  102193. this.aabb.combine(lb, c1b);
  102194. if (c1.proxy != null) {
  102195. // leaf cost = area(combined aabb)
  102196. discendingCost1 += this.aabb.surfaceArea();
  102197. } else {
  102198. // node cost = area(combined aabb) - area(old aabb)
  102199. discendingCost1 += this.aabb.surfaceArea() - c1b.surfaceArea();
  102200. }
  102201. var discendingCost2 = incrementalCost;
  102202. this.aabb.combine(lb, c2b);
  102203. if (c2.proxy != null) {
  102204. // leaf cost = area(combined aabb)
  102205. discendingCost2 += this.aabb.surfaceArea();
  102206. } else {
  102207. // node cost = area(combined aabb) - area(old aabb)
  102208. discendingCost2 += this.aabb.surfaceArea() - c2b.surfaceArea();
  102209. }
  102210. if (discendingCost1 < discendingCost2) {
  102211. if (creatingCost < discendingCost1) {
  102212. break;// stop descending
  102213. } else {
  102214. sibling = c1;// descend into first child
  102215. }
  102216. } else {
  102217. if (creatingCost < discendingCost2) {
  102218. break;// stop descending
  102219. } else {
  102220. sibling = c2;// descend into second child
  102221. }
  102222. }
  102223. }
  102224. var oldParent = sibling.parent;
  102225. var newParent;
  102226. if (this.numFreeNodes > 0) {
  102227. newParent = this.freeNodes[--this.numFreeNodes];
  102228. } else {
  102229. newParent = new OIMO.DBVTNode();
  102230. }
  102231. newParent.parent = oldParent;
  102232. newParent.child1 = leaf;
  102233. newParent.child2 = sibling;
  102234. newParent.aabb.combine(leaf.aabb, sibling.aabb);
  102235. newParent.height = sibling.height + 1;
  102236. sibling.parent = newParent;
  102237. leaf.parent = newParent;
  102238. if (sibling == this.root) {
  102239. // replace root
  102240. this.root = newParent;
  102241. } else {
  102242. // replace child
  102243. if (oldParent.child1 == sibling) {
  102244. oldParent.child1 = newParent;
  102245. } else {
  102246. oldParent.child2 = newParent;
  102247. }
  102248. }
  102249. // update whole tree
  102250. do {
  102251. newParent = this.balance(newParent);
  102252. this.fix(newParent);
  102253. newParent = newParent.parent;
  102254. } while (newParent != null);
  102255. },
  102256. getBalance: function (node) {
  102257. if (node.proxy != null) return 0;
  102258. return node.child1.height - node.child2.height;
  102259. },
  102260. /*print:function(node,indent,text){
  102261. var hasChild=node.proxy==null;
  102262. if(hasChild)text=this.print(node.child1,indent+1,text);
  102263. for(var i=indent*2;i>=0;i--){
  102264. text+=" ";
  102265. }
  102266. text+=(hasChild?this.getBalance(node):"["+node.proxy.aabb.minX+"]")+"\n";
  102267. if(hasChild)text=this.print(node.child2,indent+1,text);
  102268. return text;
  102269. },*/
  102270. /**
  102271. * Delete a leaf from the tree.
  102272. * @param node
  102273. */
  102274. deleteLeaf: function (leaf) {
  102275. if (leaf == this.root) {
  102276. this.root = null;
  102277. return;
  102278. }
  102279. var parent = leaf.parent;
  102280. var sibling;
  102281. if (parent.child1 == leaf) {
  102282. sibling = parent.child2;
  102283. } else {
  102284. sibling = parent.child1;
  102285. }
  102286. if (parent == this.root) {
  102287. this.root = sibling;
  102288. sibling.parent = null;
  102289. return;
  102290. }
  102291. var grandParent = parent.parent;
  102292. sibling.parent = grandParent;
  102293. if (grandParent.child1 == parent) {
  102294. grandParent.child1 = sibling;
  102295. } else {
  102296. grandParent.child2 = sibling;
  102297. }
  102298. if (this.numFreeNodes < 16384) {
  102299. this.freeNodes[this.numFreeNodes++] = parent;
  102300. }
  102301. do {
  102302. grandParent = this.balance(grandParent);
  102303. this.fix(grandParent);
  102304. grandParent = grandParent.parent;
  102305. } while (grandParent != null);
  102306. },
  102307. balance: function (node) {
  102308. var nh = node.height;
  102309. if (nh < 2) {
  102310. return node;
  102311. }
  102312. var p = node.parent;
  102313. var l = node.child1;
  102314. var r = node.child2;
  102315. var lh = l.height;
  102316. var rh = r.height;
  102317. var balance = lh - rh;
  102318. var t;// for bit operation
  102319. // [ N ]
  102320. // / \
  102321. // [ L ] [ R ]
  102322. // / \ / \
  102323. // [L-L] [L-R] [R-L] [R-R]
  102324. // Is the tree balanced?
  102325. if (balance > 1) {
  102326. var ll = l.child1;
  102327. var lr = l.child2;
  102328. var llh = ll.height;
  102329. var lrh = lr.height;
  102330. // Is L-L higher than L-R?
  102331. if (llh > lrh) {
  102332. // set N to L-R
  102333. l.child2 = node;
  102334. node.parent = l;
  102335. // [ L ]
  102336. // / \
  102337. // [L-L] [ N ]
  102338. // / \ / \
  102339. // [...] [...] [ L ] [ R ]
  102340. // set L-R
  102341. node.child1 = lr;
  102342. lr.parent = node;
  102343. // [ L ]
  102344. // / \
  102345. // [L-L] [ N ]
  102346. // / \ / \
  102347. // [...] [...] [L-R] [ R ]
  102348. // fix bounds and heights
  102349. node.aabb.combine(lr.aabb, r.aabb);
  102350. t = lrh - rh;
  102351. node.height = lrh - (t & t >> 31) + 1;
  102352. l.aabb.combine(ll.aabb, node.aabb);
  102353. t = llh - nh;
  102354. l.height = llh - (t & t >> 31) + 1;
  102355. } else {
  102356. // set N to L-L
  102357. l.child1 = node;
  102358. node.parent = l;
  102359. // [ L ]
  102360. // / \
  102361. // [ N ] [L-R]
  102362. // / \ / \
  102363. // [ L ] [ R ] [...] [...]
  102364. // set L-L
  102365. node.child1 = ll;
  102366. ll.parent = node;
  102367. // [ L ]
  102368. // / \
  102369. // [ N ] [L-R]
  102370. // / \ / \
  102371. // [L-L] [ R ] [...] [...]
  102372. // fix bounds and heights
  102373. node.aabb.combine(ll.aabb, r.aabb);
  102374. t = llh - rh;
  102375. node.height = llh - (t & t >> 31) + 1;
  102376. l.aabb.combine(node.aabb, lr.aabb);
  102377. t = nh - lrh;
  102378. l.height = nh - (t & t >> 31) + 1;
  102379. }
  102380. // set new parent of L
  102381. if (p != null) {
  102382. if (p.child1 == node) {
  102383. p.child1 = l;
  102384. } else {
  102385. p.child2 = l;
  102386. }
  102387. } else {
  102388. this.root = l;
  102389. }
  102390. l.parent = p;
  102391. return l;
  102392. } else if (balance < -1) {
  102393. var rl = r.child1;
  102394. var rr = r.child2;
  102395. var rlh = rl.height;
  102396. var rrh = rr.height;
  102397. // Is R-L higher than R-R?
  102398. if (rlh > rrh) {
  102399. // set N to R-R
  102400. r.child2 = node;
  102401. node.parent = r;
  102402. // [ R ]
  102403. // / \
  102404. // [R-L] [ N ]
  102405. // / \ / \
  102406. // [...] [...] [ L ] [ R ]
  102407. // set R-R
  102408. node.child2 = rr;
  102409. rr.parent = node;
  102410. // [ R ]
  102411. // / \
  102412. // [R-L] [ N ]
  102413. // / \ / \
  102414. // [...] [...] [ L ] [R-R]
  102415. // fix bounds and heights
  102416. node.aabb.combine(l.aabb, rr.aabb);
  102417. t = lh - rrh;
  102418. node.height = lh - (t & t >> 31) + 1;
  102419. r.aabb.combine(rl.aabb, node.aabb);
  102420. t = rlh - nh;
  102421. r.height = rlh - (t & t >> 31) + 1;
  102422. } else {
  102423. // set N to R-L
  102424. r.child1 = node;
  102425. node.parent = r;
  102426. // [ R ]
  102427. // / \
  102428. // [ N ] [R-R]
  102429. // / \ / \
  102430. // [ L ] [ R ] [...] [...]
  102431. // set R-L
  102432. node.child2 = rl;
  102433. rl.parent = node;
  102434. // [ R ]
  102435. // / \
  102436. // [ N ] [R-R]
  102437. // / \ / \
  102438. // [ L ] [R-L] [...] [...]
  102439. // fix bounds and heights
  102440. node.aabb.combine(l.aabb, rl.aabb);
  102441. t = lh - rlh;
  102442. node.height = lh - (t & t >> 31) + 1;
  102443. r.aabb.combine(node.aabb, rr.aabb);
  102444. t = nh - rrh;
  102445. r.height = nh - (t & t >> 31) + 1;
  102446. }
  102447. // set new parent of R
  102448. if (p != null) {
  102449. if (p.child1 == node) {
  102450. p.child1 = r;
  102451. } else {
  102452. p.child2 = r;
  102453. }
  102454. } else {
  102455. this.root = r;
  102456. }
  102457. r.parent = p;
  102458. return r;
  102459. }
  102460. return node;
  102461. },
  102462. fix: function (node) {
  102463. var c1 = node.child1;
  102464. var c2 = node.child2;
  102465. node.aabb.combine(c1.aabb, c2.aabb);
  102466. //var h1 = c1.height;
  102467. //var h2 = c2.height;
  102468. node.height = c1.height < c2.height ? c2.height + 1 : c1.height + 1;
  102469. /*if( h1 < h2 ) {
  102470. node.height = h2+1;
  102471. }else{
  102472. node.height = h1+1;
  102473. }*/
  102474. }
  102475. }
  102476. /**
  102477. * A broad-phase algorithm using dynamic bounding volume tree.
  102478. * @author saharan
  102479. * @author lo-th
  102480. */
  102481. OIMO.DBVTBroadPhase = function () {
  102482. OIMO.BroadPhase.call(this);
  102483. this.types = OIMO.BR_BOUNDING_VOLUME_TREE;
  102484. this.tree = new OIMO.DBVT();
  102485. this.stack = [];
  102486. this.leaves = [];
  102487. this.numLeaves = 0;
  102488. };
  102489. OIMO.DBVTBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  102490. OIMO.DBVTBroadPhase.prototype.constructor = OIMO.DBVTBroadPhase;
  102491. OIMO.DBVTBroadPhase.prototype.createProxy = function (shape) {
  102492. return new OIMO.DBVTProxy(shape);
  102493. };
  102494. OIMO.DBVTBroadPhase.prototype.addProxy = function (proxy) {
  102495. this.tree.insertLeaf(proxy.leaf);
  102496. this.leaves.push(proxy.leaf);
  102497. this.numLeaves++;
  102498. };
  102499. OIMO.DBVTBroadPhase.prototype.removeProxy = function (proxy) {
  102500. this.tree.deleteLeaf(proxy.leaf);
  102501. var n = this.leaves.indexOf(proxy.leaf);
  102502. if (n > -1) {
  102503. this.leaves.splice(n, 1);
  102504. this.numLeaves--;
  102505. }
  102506. };
  102507. OIMO.DBVTBroadPhase.prototype.collectPairs = function () {
  102508. if (this.numLeaves < 2) return;
  102509. var leaf, margin = 0.1, i = this.numLeaves;
  102510. while (i--) {
  102511. leaf = this.leaves[i];
  102512. if (leaf.proxy.aabb.intersectTestTwo(leaf.aabb)) {
  102513. leaf.aabb.copy(leaf.proxy.aabb, margin);
  102514. this.tree.deleteLeaf(leaf);
  102515. this.tree.insertLeaf(leaf);
  102516. this.collide(leaf, this.tree.root);
  102517. }
  102518. }
  102519. };
  102520. OIMO.DBVTBroadPhase.prototype.collide = function (node1, node2) {
  102521. var stackCount = 2;
  102522. var s1, s2, n1, n2, l1, l2;
  102523. this.stack[0] = node1;
  102524. this.stack[1] = node2;
  102525. while (stackCount > 0) {
  102526. n1 = this.stack[--stackCount];
  102527. n2 = this.stack[--stackCount];
  102528. l1 = n1.proxy != null;
  102529. l2 = n2.proxy != null;
  102530. this.numPairChecks++;
  102531. if (l1 && l2) {
  102532. s1 = n1.proxy.shape;
  102533. s2 = n2.proxy.shape;
  102534. if (s1 == s2 || s1.aabb.intersectTest(s2.aabb) || !this.isAvailablePair(s1, s2)) continue;
  102535. this.addPair(s1, s2);
  102536. } else {
  102537. if (n1.aabb.intersectTest(n2.aabb)) continue;
  102538. /*if(stackCount+4>=this.maxStack){// expand the stack
  102539. //this.maxStack<<=1;
  102540. this.maxStack*=2;
  102541. var newStack = [];// vector
  102542. newStack.length = this.maxStack;
  102543. for(var i=0;i<stackCount;i++){
  102544. newStack[i] = this.stack[i];
  102545. }
  102546. this.stack = newStack;
  102547. }*/
  102548. if (l2 || !l1 && (n1.aabb.surfaceArea() > n2.aabb.surfaceArea())) {
  102549. this.stack[stackCount++] = n1.child1;
  102550. this.stack[stackCount++] = n2;
  102551. this.stack[stackCount++] = n1.child2;
  102552. this.stack[stackCount++] = n2;
  102553. } else {
  102554. this.stack[stackCount++] = n1;
  102555. this.stack[stackCount++] = n2.child1;
  102556. this.stack[stackCount++] = n1;
  102557. this.stack[stackCount++] = n2.child2;
  102558. }
  102559. }
  102560. }
  102561. };
  102562. /**
  102563. * A node of the dynamic bounding volume tree.
  102564. * @author saharan
  102565. */
  102566. OIMO.DBVTNode = function () {
  102567. // The first child node of this node.
  102568. this.child1 = null;
  102569. // The second child node of this node.
  102570. this.child2 = null;
  102571. // The parent node of this tree.
  102572. this.parent = null;
  102573. // The proxy of this node. This has no value if this node is not leaf.
  102574. this.proxy = null;
  102575. // The maximum distance from leaf nodes.
  102576. this.height = 0;
  102577. // The AABB of this node.
  102578. this.aabb = new OIMO.AABB();
  102579. };
  102580. /**
  102581. * A proxy for dynamic bounding volume tree broad-phase.
  102582. * @author saharan
  102583. */
  102584. OIMO.DBVTProxy = function (shape) {
  102585. OIMO.Proxy.call(this, shape);
  102586. // The leaf of the proxy.
  102587. this.leaf = new OIMO.DBVTNode();
  102588. this.leaf.proxy = this;
  102589. };
  102590. OIMO.DBVTProxy.prototype = Object.create(OIMO.Proxy.prototype);
  102591. OIMO.DBVTProxy.prototype.constructor = OIMO.DBVTProxy;
  102592. OIMO.DBVTProxy.prototype.update = function () {
  102593. };
  102594. OIMO.World.prototype.add = function (obj) {
  102595. obj = obj || {};
  102596. var type = obj.type || "box";
  102597. if (typeof type === 'string') type = [type];// single shape
  102598. if (type[0].substring(0, 5) == 'joint') { // is joint
  102599. if (type[0] === 'joint') type[0] = 'jointHinge';
  102600. var axe1 = obj.axe1 || [1, 0, 0];
  102601. var axe2 = obj.axe2 || [1, 0, 0];
  102602. var pos1 = obj.pos1 || [0, 0, 0];
  102603. var pos2 = obj.pos2 || [0, 0, 0];
  102604. pos1 = pos1.map(function (x) { return x * OIMO.INV_SCALE; });
  102605. pos2 = pos2.map(function (x) { return x * OIMO.INV_SCALE; });
  102606. var min, max;
  102607. if (type[0] === "jointDistance") {
  102608. min = obj.min || 0;
  102609. max = obj.max || 10;
  102610. min = min * OIMO.INV_SCALE;
  102611. max = max * OIMO.INV_SCALE;
  102612. } else {
  102613. min = obj.min || 57.29578;
  102614. max = obj.max || 0;
  102615. min = min * OIMO.degtorad;
  102616. max = max * OIMO.degtorad;
  102617. }
  102618. var limit = obj.limit || null;
  102619. var spring = obj.spring || null;
  102620. var motor = obj.motor || null;
  102621. // joint setting
  102622. var jc = new OIMO.JointConfig();
  102623. jc.allowCollision = obj.collision || false;;
  102624. jc.localAxis1.init(axe1[0], axe1[1], axe1[2]);
  102625. jc.localAxis2.init(axe2[0], axe2[1], axe2[2]);
  102626. jc.localAnchorPoint1.init(pos1[0], pos1[1], pos1[2]);
  102627. jc.localAnchorPoint2.init(pos2[0], pos2[1], pos2[2]);
  102628. if (typeof obj.body1 == 'string' || obj.body1 instanceof String) obj.body1 = this.getByName(obj.body1);
  102629. if (typeof obj.body2 == 'string' || obj.body2 instanceof String) obj.body2 = this.getByName(obj.body2);
  102630. jc.body1 = obj.body1;
  102631. jc.body2 = obj.body2;
  102632. var joint;
  102633. switch (type[0]) {
  102634. case "jointDistance": joint = new OIMO.DistanceJoint(jc, min, max);
  102635. if (spring !== null) joint.limitMotor.setSpring(spring[0], spring[1]);
  102636. if (motor !== null) joint.limitMotor.setSpring(motor[0], motor[1]);
  102637. break;
  102638. case "jointHinge": joint = new OIMO.HingeJoint(jc, min, max);
  102639. if (spring !== null) joint.limitMotor.setSpring(spring[0], spring[1]);// soften the joint ex: 100, 0.2
  102640. if (motor !== null) joint.limitMotor.setSpring(motor[0], motor[1]);
  102641. break;
  102642. case "jointPrisme": joint = new OIMO.PrismaticJoint(jc, min, max); break;
  102643. case "jointSlide": joint = new OIMO.SliderJoint(jc, min, max); break;
  102644. case "jointBall": joint = new OIMO.BallAndSocketJoint(jc); break;
  102645. case "jointWheel": joint = new OIMO.WheelJoint(jc);
  102646. if (limit !== null) joint.rotationalLimitMotor1.setLimit(limit[0], limit[1]);
  102647. if (spring !== null) joint.rotationalLimitMotor1.setSpring(spring[0], spring[1]);
  102648. if (motor !== null) joint.rotationalLimitMotor1.setSpring(motor[0], motor[1]);
  102649. break;
  102650. }
  102651. joint.name = obj.name || '';
  102652. // finaly add to physics world
  102653. this.addJoint(joint);
  102654. return joint;
  102655. } else { // is body
  102656. // I'm dynamique or not
  102657. var move = obj.move || false;
  102658. // I can sleep or not
  102659. var noSleep = obj.noSleep || false;
  102660. // My start position
  102661. var p = obj.pos || [0, 0, 0];
  102662. p = p.map(function (x) { return x * OIMO.INV_SCALE; });
  102663. // My size
  102664. var s = obj.size || [1, 1, 1];
  102665. s = s.map(function (x) { return x * OIMO.INV_SCALE; });
  102666. // My rotation in degre
  102667. var rot = obj.rot || [0, 0, 0];
  102668. rot = rot.map(function (x) { return x * OIMO.degtorad; });
  102669. var r = [];
  102670. for (var i = 0; i < rot.length / 3; i++) {
  102671. var tmp = OIMO.EulerToAxis(rot[i + 0], rot[i + 1], rot[i + 2]);
  102672. r.push(tmp[0]); r.push(tmp[1]); r.push(tmp[2]); r.push(tmp[3]);
  102673. }
  102674. // My physics setting
  102675. var sc = new OIMO.ShapeConfig();
  102676. if (obj.sc !== undefined) sc = obj.sc;
  102677. if (obj.config) {
  102678. // The density of the shape.
  102679. sc.density = obj.config[0] === undefined ? 1 : obj.config[0];
  102680. // The coefficient of friction of the shape.
  102681. sc.friction = obj.config[1] === undefined ? 0.4 : obj.config[1];
  102682. // The coefficient of restitution of the shape.
  102683. sc.restitution = obj.config[2] === undefined ? 0.2 : obj.config[2];
  102684. // The bits of the collision groups to which the shape belongs.
  102685. sc.belongsTo = obj.config[3] || 1;
  102686. //sc.belongsTo = obj.config[3] === undefined ? 1 : obj.config[3];
  102687. // The bits of the collision groups with which the shape collides.
  102688. sc.collidesWith = obj.config[4] || 0xffffffff;
  102689. //sc.collidesWith = obj.config[4] === undefined ? 0xffffffff : obj.config[4];
  102690. }
  102691. // direct physics setting
  102692. if (obj.density !== undefined) sc.density = obj.density;
  102693. if (obj.friction !== undefined) sc.friction = obj.friction;
  102694. if (obj.restitution !== undefined) sc.restitution = obj.restitution;
  102695. if (obj.belongsTo !== undefined) sc.belongsTo = obj.belongsTo;
  102696. if (obj.collidesWith !== undefined) sc.collidesWith = obj.collidesWith;
  102697. if (obj.massPos) {
  102698. obj.massPos = obj.massPos.map(function (x) { return x * OIMO.INV_SCALE; });
  102699. sc.relativePosition.init(obj.massPos[0], obj.massPos[1], obj.massPos[2]);
  102700. }
  102701. if (obj.massRot) {
  102702. obj.massRot = obj.massRot.map(function (x) { return x * OIMO.degtorad; });
  102703. sc.relativeRotation = OIMO.EulerToMatrix(obj.massRot[0], obj.massRot[1], obj.massRot[2]);
  102704. }
  102705. // My rigidbody
  102706. var body = new OIMO.RigidBody(p[0], p[1], p[2], r[0], r[1], r[2], r[3]);
  102707. // My shapes
  102708. var shapes = [];
  102709. //if( typeof type === 'string' ) type = [type];// single shape
  102710. var n, n2;
  102711. for (var i = 0; i < type.length; i++) {
  102712. n = i * 3;
  102713. n2 = i * 4;
  102714. switch (type[i]) {
  102715. case "sphere": shapes[i] = new OIMO.SphereShape(sc, s[n]); break;
  102716. case "cylinder": shapes[i] = new OIMO.CylinderShape(sc, s[n], s[n + 1]); break;
  102717. case "box": shapes[i] = new OIMO.BoxShape(sc, s[n], s[n + 1], s[n + 2]); break;
  102718. }
  102719. body.addShape(shapes[i]);
  102720. if (i > 0) {
  102721. //shapes[i].position.init(p[0]+p[n+0], p[1]+p[n+1], p[2]+p[n+2] );
  102722. shapes[i].relativePosition = new OIMO.Vec3(p[n], p[n + 1], p[n + 2]);
  102723. if (r[n2 + 0]) shapes[i].relativeRotation = [r[n2], r[n2 + 1], r[n2 + 2], r[n2 + 3]];
  102724. }
  102725. }
  102726. // I'm static or i move
  102727. if (move) {
  102728. if (obj.massPos || obj.massRot) body.setupMass(0x1, false);
  102729. else body.setupMass(0x1, true);
  102730. if (noSleep) body.allowSleep = false;
  102731. else body.allowSleep = true;
  102732. } else {
  102733. body.setupMass(0x2);
  102734. }
  102735. body.name = obj.name || ' ';
  102736. // finaly add to physics world
  102737. this.addRigidBody(body);
  102738. return body;
  102739. }
  102740. }
  102741. //UMD simplified
  102742. var root = this;
  102743. if (!root['OIMO']) {
  102744. if (true)
  102745. module.exports = OIMO;
  102746. else if (typeof define === 'function' && define.amd)
  102747. define([], function () {
  102748. return OIMO;
  102749. });
  102750. else if (typeof exports === 'object')
  102751. exports["OIMO"] = OIMO;
  102752. else {
  102753. root["OIMO"] = OIMO;
  102754. }
  102755. }
  102756. /***/ }),
  102757. /* 19 */
  102758. /***/ (function(module, exports, __webpack_require__) {
  102759. "use strict";
  102760. Object.defineProperty(exports, "__esModule", { value: true });
  102761. var babylonjs_1 = __webpack_require__(0);
  102762. var helper_1 = __webpack_require__(3);
  102763. var TemplateManager = (function () {
  102764. function TemplateManager(containerElement) {
  102765. this.containerElement = containerElement;
  102766. this.templates = {};
  102767. this.onInit = new babylonjs_1.Observable();
  102768. this.onLoaded = new babylonjs_1.Observable();
  102769. this.onStateChange = new babylonjs_1.Observable();
  102770. this.onAllLoaded = new babylonjs_1.Observable();
  102771. this.onEventTriggered = new babylonjs_1.Observable();
  102772. this.eventManager = new eventManager_1.EventManager(this);
  102773. }
  102774. TemplateManager.prototype.initTemplate = function (templates) {
  102775. var _this = this;
  102776. var internalInit = function (dependencyMap, name, parentTemplate) {
  102777. var template = _this.templates[name];
  102778. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  102779. return internalInit(dependencyMap[childName], childName, template);
  102780. });
  102781. var addToParent = function () {
  102782. var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement;
  102783. template.appendTo(containingElement);
  102784. _this.checkLoadedState();
  102785. };
  102786. if (parentTemplate && !parentTemplate.parent) {
  102787. parentTemplate.onAppended.add(function () {
  102788. addToParent();
  102789. });
  102790. }
  102791. else {
  102792. addToParent();
  102793. }
  102794. return template;
  102795. };
  102796. return this.buildHTMLTree(templates).then(function (htmlTree) {
  102797. if (_this.templates['main']) {
  102798. internalInit(htmlTree, 'main');
  102799. }
  102800. else {
  102801. _this.checkLoadedState();
  102802. }
  102803. return;
  102804. });
  102805. };
  102806. TemplateManager.prototype.buildHTMLTree = function (templates) {
  102807. var _this = this;
  102808. var promises = Object.keys(templates).map(function (name) {
  102809. if (!templates[name])
  102810. return Promise.resolve(false);
  102811. var template = new Template(name, templates[name]);
  102812. template.onEventTriggered.add(function (eventData) { return _this.onEventTriggered.notifyObservers(eventData); });
  102813. _this.templates[name] = template;
  102814. return template.initPromise;
  102815. });
  102816. return Promise.all(promises).then(function () {
  102817. var templateStructure = {};
  102818. var buildTree = function (parentObject, name) {
  102819. _this.templates[name].isInHtmlTree = true;
  102820. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  102821. childNodes.forEach(function (element) {
  102822. parentObject[element] = {};
  102823. buildTree(parentObject[element], element);
  102824. });
  102825. };
  102826. if (_this.templates['main']) {
  102827. buildTree(templateStructure, "main");
  102828. }
  102829. return templateStructure;
  102830. });
  102831. };
  102832. TemplateManager.prototype.getCanvas = function () {
  102833. return this.containerElement.querySelector('canvas');
  102834. };
  102835. TemplateManager.prototype.getTemplate = function (name) {
  102836. return this.templates[name];
  102837. };
  102838. TemplateManager.prototype.checkLoadedState = function () {
  102839. var _this = this;
  102840. var done = Object.keys(this.templates).length === 0 || Object.keys(this.templates).every(function (key) {
  102841. return (_this.templates[key].isLoaded && !!_this.templates[key].parent) || !_this.templates[key].isInHtmlTree;
  102842. });
  102843. if (done) {
  102844. this.onAllLoaded.notifyObservers(this);
  102845. }
  102846. };
  102847. TemplateManager.prototype.dispose = function () {
  102848. var _this = this;
  102849. Object.keys(this.templates).forEach(function (template) {
  102850. _this.templates[template].dispose();
  102851. });
  102852. this.onInit.clear();
  102853. this.onAllLoaded.clear();
  102854. this.onEventTriggered.clear();
  102855. this.onLoaded.clear();
  102856. this.onStateChange.clear();
  102857. };
  102858. return TemplateManager;
  102859. }());
  102860. exports.TemplateManager = TemplateManager;
  102861. var Handlebars = __webpack_require__(20);
  102862. var eventManager_1 = __webpack_require__(21);
  102863. Handlebars.registerHelper('eachInMap', function (map, block) {
  102864. var out = '';
  102865. Object.keys(map).map(function (prop) {
  102866. var data = map[prop];
  102867. if (typeof data === 'object') {
  102868. data.id = data.id || prop;
  102869. out += block.fn(data);
  102870. }
  102871. else {
  102872. out += block.fn({ id: prop, value: data });
  102873. }
  102874. });
  102875. return out;
  102876. });
  102877. var Template = (function () {
  102878. function Template(name, _configuration) {
  102879. var _this = this;
  102880. this.name = name;
  102881. this._configuration = _configuration;
  102882. this.onInit = new babylonjs_1.Observable();
  102883. this.onLoaded = new babylonjs_1.Observable();
  102884. this.onAppended = new babylonjs_1.Observable();
  102885. this.onStateChange = new babylonjs_1.Observable();
  102886. this.onEventTriggered = new babylonjs_1.Observable();
  102887. this.loadRequests = [];
  102888. this.isLoaded = false;
  102889. this.isShown = false;
  102890. this.isInHtmlTree = false;
  102891. this.onInit.notifyObservers(this);
  102892. var htmlContentPromise = this.getTemplateAsHtml(_configuration);
  102893. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  102894. if (htmlTemplate) {
  102895. _this.htmlTemplate = htmlTemplate;
  102896. var compiledTemplate = Handlebars.compile(htmlTemplate);
  102897. var config = _this._configuration.params || {};
  102898. var rawHtml = compiledTemplate(config);
  102899. _this.fragment = document.createRange().createContextualFragment(rawHtml);
  102900. _this.isLoaded = true;
  102901. _this.isShown = true;
  102902. _this.onLoaded.notifyObservers(_this);
  102903. }
  102904. return _this;
  102905. });
  102906. }
  102907. Template.prototype.updateParams = function (params) {
  102908. this._configuration.params = params;
  102909. if (this.isLoaded) {
  102910. this.dispose();
  102911. }
  102912. var compiledTemplate = Handlebars.compile(this.htmlTemplate);
  102913. var config = this._configuration.params || {};
  102914. var rawHtml = compiledTemplate(config);
  102915. this.fragment = document.createRange().createContextualFragment(rawHtml);
  102916. if (this.parent) {
  102917. this.appendTo(this.parent, true);
  102918. }
  102919. };
  102920. Object.defineProperty(Template.prototype, "configuration", {
  102921. get: function () {
  102922. return this._configuration;
  102923. },
  102924. enumerable: true,
  102925. configurable: true
  102926. });
  102927. Template.prototype.getChildElements = function () {
  102928. var childrenArray = [];
  102929. var children = this.fragment.children;
  102930. if (!children) {
  102931. children = this.fragment.querySelectorAll('*');
  102932. }
  102933. for (var i = 0; i < children.length; ++i) {
  102934. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  102935. }
  102936. return childrenArray;
  102937. };
  102938. Template.prototype.appendTo = function (parent, forceRemove) {
  102939. var _this = this;
  102940. if (this.parent) {
  102941. if (forceRemove) {
  102942. this.parent.removeChild(this.fragment);
  102943. }
  102944. else {
  102945. return;
  102946. }
  102947. }
  102948. this.parent = parent;
  102949. if (this._configuration.id) {
  102950. this.parent.id = this._configuration.id;
  102951. }
  102952. this.fragment = this.parent.appendChild(this.fragment);
  102953. setTimeout(function () {
  102954. _this.registerEvents();
  102955. _this.onAppended.notifyObservers(_this);
  102956. });
  102957. };
  102958. Template.prototype.show = function (visibilityFunction) {
  102959. var _this = this;
  102960. if (this.isHiding)
  102961. return Promise.resolve(this);
  102962. return Promise.resolve().then(function () {
  102963. _this.isShowing = true;
  102964. if (visibilityFunction) {
  102965. return visibilityFunction(_this);
  102966. }
  102967. else {
  102968. _this.parent.style.display = 'flex';
  102969. return _this;
  102970. }
  102971. }).then(function () {
  102972. _this.isShown = true;
  102973. _this.isShowing = false;
  102974. _this.onStateChange.notifyObservers(_this);
  102975. return _this;
  102976. });
  102977. };
  102978. Template.prototype.hide = function (visibilityFunction) {
  102979. var _this = this;
  102980. if (this.isShowing)
  102981. return Promise.resolve(this);
  102982. return Promise.resolve().then(function () {
  102983. _this.isHiding = true;
  102984. if (visibilityFunction) {
  102985. return visibilityFunction(_this);
  102986. }
  102987. else {
  102988. _this.parent.style.display = 'hide';
  102989. return _this;
  102990. }
  102991. }).then(function () {
  102992. _this.isShown = false;
  102993. _this.isHiding = false;
  102994. _this.onStateChange.notifyObservers(_this);
  102995. return _this;
  102996. });
  102997. };
  102998. Template.prototype.dispose = function () {
  102999. this.onAppended.clear();
  103000. this.onEventTriggered.clear();
  103001. this.onInit.clear();
  103002. this.onLoaded.clear();
  103003. this.onStateChange.clear();
  103004. this.isLoaded = false;
  103005. this.parent.removeChild(this.fragment);
  103006. this.loadRequests.forEach(function (request) {
  103007. request.abort();
  103008. });
  103009. };
  103010. Template.prototype.getTemplateAsHtml = function (templateConfig) {
  103011. var _this = this;
  103012. if (!templateConfig) {
  103013. return Promise.reject('No templateConfig provided');
  103014. }
  103015. else if (templateConfig.html !== undefined) {
  103016. return Promise.resolve(templateConfig.html);
  103017. }
  103018. else {
  103019. var location_1 = getTemplateLocation(templateConfig);
  103020. if (helper_1.isUrl(location_1)) {
  103021. return new Promise(function (resolve, reject) {
  103022. var fileRequest = babylonjs_1.Tools.LoadFile(location_1, function (data) {
  103023. resolve(data);
  103024. }, undefined, undefined, false, function (request, error) {
  103025. reject(error);
  103026. });
  103027. _this.loadRequests.push(fileRequest);
  103028. });
  103029. }
  103030. else {
  103031. location_1 = location_1.replace('#', '');
  103032. var element = document.getElementById(location_1);
  103033. if (element) {
  103034. return Promise.resolve(element.innerHTML);
  103035. }
  103036. else {
  103037. return Promise.reject('Template ID not found');
  103038. }
  103039. }
  103040. }
  103041. };
  103042. Template.prototype.registerEvents = function () {
  103043. var _this = this;
  103044. this.registeredEvents = this.registeredEvents || [];
  103045. if (this.registeredEvents.length) {
  103046. this.registeredEvents.forEach(function (evt) {
  103047. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  103048. });
  103049. }
  103050. if (this._configuration.events) {
  103051. var _loop_1 = function (eventName) {
  103052. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  103053. var functionToFire_1 = function (selector, event) {
  103054. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  103055. };
  103056. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  103057. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, '#' + this_1.parent.id), false);
  103058. }
  103059. else if (typeof this_1._configuration.events[eventName] === 'object') {
  103060. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  103061. var event_1 = this_1._configuration.events[eventName] || {};
  103062. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  103063. if (selector && selector.indexOf('#') !== 0) {
  103064. selector = '#' + selector;
  103065. }
  103066. var htmlElement = _this.parent.querySelector(selector);
  103067. if (htmlElement) {
  103068. var binding = functionToFire_1.bind(_this, selector);
  103069. htmlElement.addEventListener(eventName, binding, false);
  103070. _this.registeredEvents.push({
  103071. htmlElement: htmlElement,
  103072. eventName: eventName,
  103073. function: binding
  103074. });
  103075. }
  103076. });
  103077. }
  103078. }
  103079. };
  103080. var this_1 = this;
  103081. for (var eventName in this._configuration.events) {
  103082. _loop_1(eventName);
  103083. }
  103084. }
  103085. };
  103086. return Template;
  103087. }());
  103088. exports.Template = Template;
  103089. function getTemplateLocation(templateConfig) {
  103090. if (!templateConfig || typeof templateConfig === 'string') {
  103091. return templateConfig;
  103092. }
  103093. else {
  103094. return templateConfig.location;
  103095. }
  103096. }
  103097. exports.getTemplateLocation = getTemplateLocation;
  103098. /***/ }),
  103099. /* 20 */
  103100. /***/ (function(module, exports, __webpack_require__) {
  103101. /**!
  103102. @license
  103103. handlebars v4.0.11
  103104. Copyright (C) 2011-2017 by Yehuda Katz
  103105. Permission is hereby granted, free of charge, to any person obtaining a copy
  103106. of this software and associated documentation files (the "Software"), to deal
  103107. in the Software without restriction, including without limitation the rights
  103108. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  103109. copies of the Software, and to permit persons to whom the Software is
  103110. furnished to do so, subject to the following conditions:
  103111. The above copyright notice and this permission notice shall be included in
  103112. all copies or substantial portions of the Software.
  103113. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  103114. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  103115. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  103116. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  103117. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  103118. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  103119. THE SOFTWARE.
  103120. */
  103121. !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],
  103122. 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){
  103123. 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"]}])});
  103124. /***/ }),
  103125. /* 21 */
  103126. /***/ (function(module, exports, __webpack_require__) {
  103127. "use strict";
  103128. Object.defineProperty(exports, "__esModule", { value: true });
  103129. var EventManager = (function () {
  103130. function EventManager(templateManager) {
  103131. var _this = this;
  103132. this.templateManager = templateManager;
  103133. this.callbacksContainer = {};
  103134. this.templateManager.onEventTriggered.add(function (eventData) {
  103135. _this.eventTriggered(eventData);
  103136. });
  103137. }
  103138. EventManager.prototype.registerCallback = function (templateName, callback, eventType, selector) {
  103139. if (!this.callbacksContainer[templateName]) {
  103140. this.callbacksContainer[templateName] = [];
  103141. }
  103142. this.callbacksContainer[templateName].push({
  103143. eventType: eventType,
  103144. callback: callback
  103145. });
  103146. };
  103147. EventManager.prototype.unregisterCallback = function (templateName, callback, eventType, selector) {
  103148. var callbackDefs = this.callbacksContainer[templateName] || [];
  103149. this.callbacksContainer[templateName] = callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); });
  103150. };
  103151. EventManager.prototype.eventTriggered = function (data) {
  103152. var templateName = data.template.name;
  103153. var eventType = data.event.type;
  103154. var selector = data.selector;
  103155. var callbackDefs = this.callbacksContainer[templateName] || [];
  103156. callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); }).forEach(function (callbackDef) {
  103157. callbackDef.callback(data);
  103158. });
  103159. };
  103160. return EventManager;
  103161. }());
  103162. exports.EventManager = EventManager;
  103163. /***/ }),
  103164. /* 22 */
  103165. /***/ (function(module, exports, __webpack_require__) {
  103166. "use strict";
  103167. Object.defineProperty(exports, "__esModule", { value: true });
  103168. var mappers_1 = __webpack_require__(1);
  103169. var types_1 = __webpack_require__(23);
  103170. var deepmerge = __webpack_require__(14);
  103171. var babylonjs_1 = __webpack_require__(0);
  103172. var ConfigurationLoader = (function () {
  103173. function ConfigurationLoader() {
  103174. this.configurationCache = {};
  103175. this.loadRequests = [];
  103176. }
  103177. ConfigurationLoader.prototype.loadConfiguration = function (initConfig, callback) {
  103178. var _this = this;
  103179. if (initConfig === void 0) { initConfig = {}; }
  103180. var loadedConfig = deepmerge({}, initConfig);
  103181. var extendedConfiguration = types_1.getConfigurationType(loadedConfig.extends || "");
  103182. loadedConfig = deepmerge(extendedConfiguration, loadedConfig);
  103183. if (loadedConfig.configuration) {
  103184. var mapperType_1 = "json";
  103185. return Promise.resolve().then(function () {
  103186. if (typeof loadedConfig.configuration === "string" || (loadedConfig.configuration && loadedConfig.configuration.url)) {
  103187. var url = '';
  103188. if (typeof loadedConfig.configuration === "string") {
  103189. url = loadedConfig.configuration;
  103190. }
  103191. if (typeof loadedConfig.configuration === "object" && loadedConfig.configuration.url) {
  103192. url = loadedConfig.configuration.url;
  103193. var type = loadedConfig.configuration.mapper;
  103194. if (!type) {
  103195. type = loadedConfig.configuration.url.split('.').pop();
  103196. }
  103197. mapperType_1 = type || mapperType_1;
  103198. }
  103199. return _this.loadFile(url);
  103200. }
  103201. else {
  103202. if (typeof loadedConfig.configuration === "object") {
  103203. mapperType_1 = loadedConfig.configuration.mapper || mapperType_1;
  103204. return loadedConfig.configuration.payload || {};
  103205. }
  103206. return {};
  103207. }
  103208. }).then(function (data) {
  103209. var mapper = mappers_1.mapperManager.getMapper(mapperType_1);
  103210. var parsed = mapper.map(data);
  103211. var merged = deepmerge(loadedConfig, parsed);
  103212. if (callback)
  103213. callback(merged);
  103214. return merged;
  103215. });
  103216. }
  103217. else {
  103218. if (callback)
  103219. callback(loadedConfig);
  103220. return Promise.resolve(loadedConfig);
  103221. }
  103222. };
  103223. ConfigurationLoader.prototype.dispose = function () {
  103224. this.loadRequests.forEach(function (request) {
  103225. request.abort();
  103226. });
  103227. };
  103228. ConfigurationLoader.prototype.loadFile = function (url) {
  103229. var _this = this;
  103230. var cacheReference = this.configurationCache;
  103231. if (cacheReference[url]) {
  103232. return Promise.resolve(cacheReference[url]);
  103233. }
  103234. return new Promise(function (resolve, reject) {
  103235. var fileRequest = babylonjs_1.Tools.LoadFile(url, resolve, undefined, undefined, false, function (request, error) {
  103236. reject(error);
  103237. });
  103238. _this.loadRequests.push(fileRequest);
  103239. });
  103240. };
  103241. return ConfigurationLoader;
  103242. }());
  103243. exports.ConfigurationLoader = ConfigurationLoader;
  103244. exports.configurationLoader = new ConfigurationLoader();
  103245. exports.default = exports.configurationLoader;
  103246. /***/ }),
  103247. /* 23 */
  103248. /***/ (function(module, exports, __webpack_require__) {
  103249. "use strict";
  103250. Object.defineProperty(exports, "__esModule", { value: true });
  103251. var minimal_1 = __webpack_require__(24);
  103252. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  103253. var default_1 = __webpack_require__(25);
  103254. exports.defaultConfiguration = default_1.defaultConfiguration;
  103255. var getConfigurationType = function (type) {
  103256. switch (type) {
  103257. case 'default':
  103258. return default_1.defaultConfiguration;
  103259. case 'minimal':
  103260. return minimal_1.minimalConfiguration;
  103261. case 'none':
  103262. return {};
  103263. default:
  103264. return default_1.defaultConfiguration;
  103265. }
  103266. };
  103267. exports.getConfigurationType = getConfigurationType;
  103268. /***/ }),
  103269. /* 24 */
  103270. /***/ (function(module, exports, __webpack_require__) {
  103271. "use strict";
  103272. Object.defineProperty(exports, "__esModule", { value: true });
  103273. exports.minimalConfiguration = {
  103274. version: "0.1",
  103275. templates: {
  103276. main: {
  103277. html: __webpack_require__(7)
  103278. },
  103279. loadingScreen: {
  103280. html: __webpack_require__(8),
  103281. params: {
  103282. backgroundColor: "#000000",
  103283. loadingImage: __webpack_require__(9)
  103284. }
  103285. },
  103286. viewer: {
  103287. html: __webpack_require__(10),
  103288. },
  103289. overlay: {
  103290. html: __webpack_require__(11),
  103291. params: {
  103292. closeImage: __webpack_require__(12),
  103293. closeText: 'Close'
  103294. }
  103295. },
  103296. error: {
  103297. html: __webpack_require__(13)
  103298. }
  103299. },
  103300. engine: {
  103301. antialiasing: true
  103302. }
  103303. };
  103304. /***/ }),
  103305. /* 25 */
  103306. /***/ (function(module, exports, __webpack_require__) {
  103307. "use strict";
  103308. Object.defineProperty(exports, "__esModule", { value: true });
  103309. exports.defaultConfiguration = {
  103310. version: "3.2.0-alpha4",
  103311. templates: {
  103312. main: {
  103313. html: __webpack_require__(7)
  103314. },
  103315. loadingScreen: {
  103316. html: __webpack_require__(8),
  103317. params: {
  103318. backgroundColor: "#000000",
  103319. loadingImage: __webpack_require__(9)
  103320. }
  103321. },
  103322. viewer: {
  103323. html: __webpack_require__(10),
  103324. events: {
  103325. pointerout: true,
  103326. pointerdown: true,
  103327. pointerup: true
  103328. }
  103329. },
  103330. navBar: {
  103331. html: __webpack_require__(26),
  103332. params: {
  103333. buttons: {
  103334. "fullscreen-button": {
  103335. altText: "Fullscreen",
  103336. image: __webpack_require__(27)
  103337. }
  103338. },
  103339. visibilityTimeout: 2000
  103340. },
  103341. events: {
  103342. pointerdown: { 'fullscreen-button': true },
  103343. pointerover: true
  103344. }
  103345. },
  103346. overlay: {
  103347. html: __webpack_require__(11),
  103348. params: {
  103349. closeImage: __webpack_require__(12),
  103350. closeText: 'Close'
  103351. }
  103352. },
  103353. help: {
  103354. html: __webpack_require__(28)
  103355. },
  103356. share: {
  103357. html: __webpack_require__(29)
  103358. },
  103359. error: {
  103360. html: __webpack_require__(13)
  103361. }
  103362. },
  103363. camera: {
  103364. behaviors: {
  103365. autoRotate: 0,
  103366. framing: {
  103367. type: 2,
  103368. zoomOnBoundingInfo: true,
  103369. zoomStopsAnimation: false
  103370. }
  103371. }
  103372. },
  103373. skybox: {
  103374. pbr: true,
  103375. blur: 0.7,
  103376. infiniteDIstance: false,
  103377. },
  103378. ground: true,
  103379. engine: {
  103380. antialiasing: true
  103381. },
  103382. scene: {
  103383. imageProcessingConfiguration: {
  103384. exposure: 1.4,
  103385. contrast: 1.66,
  103386. toneMappingEnabled: true
  103387. }
  103388. }
  103389. };
  103390. /***/ }),
  103391. /* 26 */
  103392. /***/ (function(module, exports) {
  103393. 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>";
  103394. /***/ }),
  103395. /* 27 */
  103396. /***/ (function(module, exports) {
  103397. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQAAAAB/ecQqAAAAAnRSTlMAAHaTzTgAAAAeSURBVHgBY6ASsP/A/wcXZQNGhCkyAfE24HUndQAAXlkXcQ24P7gAAAAASUVORK5CYII="
  103398. /***/ }),
  103399. /* 28 */
  103400. /***/ (function(module, exports) {
  103401. module.exports = "HELP";
  103402. /***/ }),
  103403. /* 29 */
  103404. /***/ (function(module, exports) {
  103405. module.exports = "SHARE";
  103406. /***/ }),
  103407. /* 30 */
  103408. /***/ (function(module, exports, __webpack_require__) {
  103409. /* WEBPACK VAR INJECTION */(function(global) {var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  103410. var babylonDependency = (globalObject && globalObject.BABYLON) || BABYLON || ("function" !== 'undefined' && __webpack_require__(0));
  103411. var BABYLON = babylonDependency;
  103412. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  103413. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  103414. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  103415. 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;
  103416. return c > 3 && r && Object.defineProperty(target, key, r), r;
  103417. };
  103418. var __extends = (this && this.__extends) || (function () {
  103419. var extendStatics = Object.setPrototypeOf ||
  103420. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  103421. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  103422. return function (d, b) {
  103423. extendStatics(d, b);
  103424. function __() { this.constructor = d; }
  103425. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  103426. };
  103427. })();
  103428. var BABYLON;
  103429. (function (BABYLON) {
  103430. var STLFileLoader = /** @class */ (function () {
  103431. function STLFileLoader() {
  103432. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  103433. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  103434. 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;
  103435. 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;
  103436. this.name = "stl";
  103437. // force data to come in as an ArrayBuffer
  103438. // we'll convert to string if it looks like it's an ASCII .stl
  103439. this.extensions = {
  103440. ".stl": { isBinary: true },
  103441. };
  103442. }
  103443. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  103444. var matches;
  103445. if (this.isBinary(data)) {
  103446. // binary .stl
  103447. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  103448. this.parseBinary(babylonMesh, data);
  103449. if (meshes) {
  103450. meshes.push(babylonMesh);
  103451. }
  103452. return true;
  103453. }
  103454. // ASCII .stl
  103455. // convert to string
  103456. var array_buffer = new Uint8Array(data);
  103457. var str = '';
  103458. for (var i = 0; i < data.byteLength; i++) {
  103459. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  103460. }
  103461. data = str;
  103462. while (matches = this.solidPattern.exec(data)) {
  103463. var meshName = matches[1];
  103464. var meshNameFromEnd = matches[3];
  103465. if (meshName != meshNameFromEnd) {
  103466. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  103467. return false;
  103468. }
  103469. // check meshesNames
  103470. if (meshesNames && meshName) {
  103471. if (meshesNames instanceof Array) {
  103472. if (!meshesNames.indexOf(meshName)) {
  103473. continue;
  103474. }
  103475. }
  103476. else {
  103477. if (meshName !== meshesNames) {
  103478. continue;
  103479. }
  103480. }
  103481. }
  103482. // stl mesh name can be empty as well
  103483. meshName = meshName || "stlmesh";
  103484. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  103485. this.parseASCII(babylonMesh, matches[2]);
  103486. if (meshes) {
  103487. meshes.push(babylonMesh);
  103488. }
  103489. }
  103490. return true;
  103491. };
  103492. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  103493. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  103494. if (result) {
  103495. scene.createDefaultCameraOrLight();
  103496. }
  103497. return result;
  103498. };
  103499. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  103500. var container = new BABYLON.AssetContainer(scene);
  103501. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  103502. container.removeAllFromScene();
  103503. return container;
  103504. };
  103505. STLFileLoader.prototype.isBinary = function (data) {
  103506. // check if file size is correct for binary stl
  103507. var faceSize, nFaces, reader;
  103508. reader = new DataView(data);
  103509. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  103510. nFaces = reader.getUint32(80, true);
  103511. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  103512. return true;
  103513. }
  103514. // check characters higher than ASCII to confirm binary
  103515. var fileLength = reader.byteLength;
  103516. for (var index = 0; index < fileLength; index++) {
  103517. if (reader.getUint8(index) > 127) {
  103518. return true;
  103519. }
  103520. }
  103521. return false;
  103522. };
  103523. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  103524. var reader = new DataView(data);
  103525. var faces = reader.getUint32(80, true);
  103526. var dataOffset = 84;
  103527. var faceLength = 12 * 4 + 2;
  103528. var offset = 0;
  103529. var positions = new Float32Array(faces * 3 * 3);
  103530. var normals = new Float32Array(faces * 3 * 3);
  103531. var indices = new Uint32Array(faces * 3);
  103532. var indicesCount = 0;
  103533. for (var face = 0; face < faces; face++) {
  103534. var start = dataOffset + face * faceLength;
  103535. var normalX = reader.getFloat32(start, true);
  103536. var normalY = reader.getFloat32(start + 4, true);
  103537. var normalZ = reader.getFloat32(start + 8, true);
  103538. for (var i = 1; i <= 3; i++) {
  103539. var vertexstart = start + i * 12;
  103540. // ordering is intentional to match ascii import
  103541. positions[offset] = reader.getFloat32(vertexstart, true);
  103542. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  103543. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  103544. normals[offset] = normalX;
  103545. normals[offset + 2] = normalY;
  103546. normals[offset + 1] = normalZ;
  103547. offset += 3;
  103548. }
  103549. indices[indicesCount] = indicesCount++;
  103550. indices[indicesCount] = indicesCount++;
  103551. indices[indicesCount] = indicesCount++;
  103552. }
  103553. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  103554. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  103555. mesh.setIndices(indices);
  103556. mesh.computeWorldMatrix(true);
  103557. };
  103558. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  103559. var positions = [];
  103560. var normals = [];
  103561. var indices = [];
  103562. var indicesCount = 0;
  103563. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  103564. var matches;
  103565. while (matches = this.facetsPattern.exec(solidData)) {
  103566. var facet = matches[1];
  103567. //one normal per face
  103568. var normalMatches = this.normalPattern.exec(facet);
  103569. this.normalPattern.lastIndex = 0;
  103570. if (!normalMatches) {
  103571. continue;
  103572. }
  103573. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  103574. var vertexMatch;
  103575. while (vertexMatch = this.vertexPattern.exec(facet)) {
  103576. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  103577. normals.push(normal[0], normal[1], normal[2]);
  103578. }
  103579. indices.push(indicesCount++, indicesCount++, indicesCount++);
  103580. this.vertexPattern.lastIndex = 0;
  103581. }
  103582. this.facetsPattern.lastIndex = 0;
  103583. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  103584. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  103585. mesh.setIndices(indices);
  103586. mesh.computeWorldMatrix(true);
  103587. };
  103588. return STLFileLoader;
  103589. }());
  103590. BABYLON.STLFileLoader = STLFileLoader;
  103591. if (BABYLON.SceneLoader) {
  103592. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  103593. }
  103594. })(BABYLON || (BABYLON = {}));
  103595. //# sourceMappingURL=babylon.stlFileLoader.js.map
  103596. var BABYLON;
  103597. (function (BABYLON) {
  103598. /**
  103599. * Class reading and parsing the MTL file bundled with the obj file.
  103600. */
  103601. var MTLFileLoader = /** @class */ (function () {
  103602. function MTLFileLoader() {
  103603. // All material loaded from the mtl will be set here
  103604. this.materials = [];
  103605. }
  103606. /**
  103607. * This function will read the mtl file and create each material described inside
  103608. * This function could be improve by adding :
  103609. * -some component missing (Ni, Tf...)
  103610. * -including the specific options available
  103611. *
  103612. * @param scene
  103613. * @param data
  103614. * @param rootUrl
  103615. */
  103616. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  103617. //Split the lines from the file
  103618. var lines = data.split('\n');
  103619. //Space char
  103620. var delimiter_pattern = /\s+/;
  103621. //Array with RGB colors
  103622. var color;
  103623. //New material
  103624. var material = null;
  103625. //Look at each line
  103626. for (var i = 0; i < lines.length; i++) {
  103627. var line = lines[i].trim();
  103628. // Blank line or comment
  103629. if (line.length === 0 || line.charAt(0) === '#') {
  103630. continue;
  103631. }
  103632. //Get the first parameter (keyword)
  103633. var pos = line.indexOf(' ');
  103634. var key = (pos >= 0) ? line.substring(0, pos) : line;
  103635. key = key.toLowerCase();
  103636. //Get the data following the key
  103637. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  103638. //This mtl keyword will create the new material
  103639. if (key === "newmtl") {
  103640. //Check if it is the first material.
  103641. // Materials specifications are described after this keyword.
  103642. if (material) {
  103643. //Add the previous material in the material array.
  103644. this.materials.push(material);
  103645. }
  103646. //Create a new material.
  103647. // value is the name of the material read in the mtl file
  103648. material = new BABYLON.StandardMaterial(value, scene);
  103649. }
  103650. else if (key === "kd" && material) {
  103651. // Diffuse color (color under white light) using RGB values
  103652. //value = "r g b"
  103653. color = value.split(delimiter_pattern, 3).map(parseFloat);
  103654. //color = [r,g,b]
  103655. //Set tghe color into the material
  103656. material.diffuseColor = BABYLON.Color3.FromArray(color);
  103657. }
  103658. else if (key === "ka" && material) {
  103659. // Ambient color (color under shadow) using RGB values
  103660. //value = "r g b"
  103661. color = value.split(delimiter_pattern, 3).map(parseFloat);
  103662. //color = [r,g,b]
  103663. //Set tghe color into the material
  103664. material.ambientColor = BABYLON.Color3.FromArray(color);
  103665. }
  103666. else if (key === "ks" && material) {
  103667. // Specular color (color when light is reflected from shiny surface) using RGB values
  103668. //value = "r g b"
  103669. color = value.split(delimiter_pattern, 3).map(parseFloat);
  103670. //color = [r,g,b]
  103671. //Set the color into the material
  103672. material.specularColor = BABYLON.Color3.FromArray(color);
  103673. }
  103674. else if (key === "ke" && material) {
  103675. // Emissive color using RGB values
  103676. color = value.split(delimiter_pattern, 3).map(parseFloat);
  103677. material.emissiveColor = BABYLON.Color3.FromArray(color);
  103678. }
  103679. else if (key === "ns" && material) {
  103680. //value = "Integer"
  103681. material.specularPower = parseFloat(value);
  103682. }
  103683. else if (key === "d" && material) {
  103684. //d is dissolve for current material. It mean alpha for BABYLON
  103685. material.alpha = parseFloat(value);
  103686. //Texture
  103687. //This part can be improved by adding the possible options of texture
  103688. }
  103689. else if (key === "map_ka" && material) {
  103690. // ambient texture map with a loaded image
  103691. //We must first get the folder of the image
  103692. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  103693. }
  103694. else if (key === "map_kd" && material) {
  103695. // Diffuse texture map with a loaded image
  103696. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  103697. }
  103698. else if (key === "map_ks" && material) {
  103699. // Specular texture map with a loaded image
  103700. //We must first get the folder of the image
  103701. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  103702. }
  103703. else if (key === "map_ns") {
  103704. //Specular
  103705. //Specular highlight component
  103706. //We must first get the folder of the image
  103707. //
  103708. //Not supported by BABYLON
  103709. //
  103710. // continue;
  103711. }
  103712. else if (key === "map_bump" && material) {
  103713. //The bump texture
  103714. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  103715. }
  103716. else if (key === "map_d" && material) {
  103717. // The dissolve of the material
  103718. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  103719. //Options for illumination
  103720. }
  103721. else if (key === "illum") {
  103722. //Illumination
  103723. if (value === "0") {
  103724. //That mean Kd == Kd
  103725. }
  103726. else if (value === "1") {
  103727. //Color on and Ambient on
  103728. }
  103729. else if (value === "2") {
  103730. //Highlight on
  103731. }
  103732. else if (value === "3") {
  103733. //Reflection on and Ray trace on
  103734. }
  103735. else if (value === "4") {
  103736. //Transparency: Glass on, Reflection: Ray trace on
  103737. }
  103738. else if (value === "5") {
  103739. //Reflection: Fresnel on and Ray trace on
  103740. }
  103741. else if (value === "6") {
  103742. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  103743. }
  103744. else if (value === "7") {
  103745. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  103746. }
  103747. else if (value === "8") {
  103748. //Reflection on and Ray trace off
  103749. }
  103750. else if (value === "9") {
  103751. //Transparency: Glass on, Reflection: Ray trace off
  103752. }
  103753. else if (value === "10") {
  103754. //Casts shadows onto invisible surfaces
  103755. }
  103756. }
  103757. else {
  103758. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  103759. }
  103760. }
  103761. //At the end of the file, add the last material
  103762. if (material) {
  103763. this.materials.push(material);
  103764. }
  103765. };
  103766. /**
  103767. * Gets the texture for the material.
  103768. *
  103769. * If the material is imported from input file,
  103770. * We sanitize the url to ensure it takes the textre from aside the material.
  103771. *
  103772. * @param rootUrl The root url to load from
  103773. * @param value The value stored in the mtl
  103774. * @return The Texture
  103775. */
  103776. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  103777. if (!value) {
  103778. return null;
  103779. }
  103780. var url = rootUrl;
  103781. // Load from input file.
  103782. if (rootUrl === "file:") {
  103783. var lastDelimiter = value.lastIndexOf("\\");
  103784. if (lastDelimiter === -1) {
  103785. lastDelimiter = value.lastIndexOf("/");
  103786. }
  103787. if (lastDelimiter > -1) {
  103788. url += value.substr(lastDelimiter + 1);
  103789. }
  103790. else {
  103791. url += value;
  103792. }
  103793. }
  103794. else {
  103795. url += value;
  103796. }
  103797. return new BABYLON.Texture(url, scene);
  103798. };
  103799. return MTLFileLoader;
  103800. }());
  103801. BABYLON.MTLFileLoader = MTLFileLoader;
  103802. var OBJFileLoader = /** @class */ (function () {
  103803. function OBJFileLoader() {
  103804. this.name = "obj";
  103805. this.extensions = ".obj";
  103806. this.obj = /^o/;
  103807. this.group = /^g/;
  103808. this.mtllib = /^mtllib /;
  103809. this.usemtl = /^usemtl /;
  103810. this.smooth = /^s /;
  103811. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  103812. // vn float float float
  103813. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  103814. // vt float float
  103815. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  103816. // f vertex vertex vertex ...
  103817. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  103818. // f vertex/uvs vertex/uvs vertex/uvs ...
  103819. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  103820. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  103821. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  103822. // f vertex//normal vertex//normal vertex//normal ...
  103823. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  103824. }
  103825. /**
  103826. * Calls synchronously the MTL file attached to this obj.
  103827. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  103828. * Without this function materials are not displayed in the first frame (but displayed after).
  103829. * In consequence it is impossible to get material information in your HTML file
  103830. *
  103831. * @param url The URL of the MTL file
  103832. * @param rootUrl
  103833. * @param onSuccess Callback function to be called when the MTL file is loaded
  103834. * @private
  103835. */
  103836. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  103837. //The complete path to the mtl file
  103838. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  103839. // Loads through the babylon tools to allow fileInput search.
  103840. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  103841. };
  103842. OBJFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  103843. //get the meshes from OBJ file
  103844. var loadedMeshes = this._parseSolid(meshesNames, scene, data, rootUrl);
  103845. //Push meshes from OBJ file into the variable mesh of this function
  103846. if (meshes) {
  103847. loadedMeshes.forEach(function (mesh) {
  103848. meshes.push(mesh);
  103849. });
  103850. }
  103851. return true;
  103852. };
  103853. OBJFileLoader.prototype.load = function (scene, data, rootUrl) {
  103854. //Get the 3D model
  103855. return this.importMesh(null, scene, data, rootUrl, null, null, null);
  103856. };
  103857. OBJFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  103858. var container = new BABYLON.AssetContainer(scene);
  103859. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  103860. container.removeAllFromScene();
  103861. return container;
  103862. };
  103863. /**
  103864. * Read the OBJ file and create an Array of meshes.
  103865. * Each mesh contains all information given by the OBJ and the MTL file.
  103866. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  103867. *
  103868. * @param meshesNames
  103869. * @param scene BABYLON.Scene The scene where are displayed the data
  103870. * @param data String The content of the obj file
  103871. * @param rootUrl String The path to the folder
  103872. * @returns Array<AbstractMesh>
  103873. * @private
  103874. */
  103875. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  103876. var positions = []; //values for the positions of vertices
  103877. var normals = []; //Values for the normals
  103878. var uvs = []; //Values for the textures
  103879. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  103880. var handledMesh; //The current mesh of meshes array
  103881. var indicesForBabylon = []; //The list of indices for VertexData
  103882. var wrappedPositionForBabylon = []; //The list of position in vectors
  103883. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  103884. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  103885. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  103886. var curPositionInIndices = 0;
  103887. var hasMeshes = false; //Meshes are defined in the file
  103888. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  103889. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  103890. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  103891. var triangles = []; //Indices from new triangles coming from polygons
  103892. var materialNameFromObj = ""; //The name of the current material
  103893. var fileToLoad = ""; //The name of the mtlFile to load
  103894. var materialsFromMTLFile = new MTLFileLoader();
  103895. var objMeshName = ""; //The name of the current obj mesh
  103896. var increment = 1; //Id for meshes created by the multimaterial
  103897. var isFirstMaterial = true;
  103898. /**
  103899. * Search for obj in the given array.
  103900. * This function is called to check if a couple of data already exists in an array.
  103901. *
  103902. * If found, returns the index of the founded tuple index. Returns -1 if not found
  103903. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  103904. * @param obj Array<number>
  103905. * @returns {boolean}
  103906. */
  103907. var isInArray = function (arr, obj) {
  103908. if (!arr[obj[0]])
  103909. arr[obj[0]] = { normals: [], idx: [] };
  103910. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  103911. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  103912. };
  103913. var isInArrayUV = function (arr, obj) {
  103914. if (!arr[obj[0]])
  103915. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  103916. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  103917. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  103918. return arr[obj[0]].idx[idx];
  103919. }
  103920. return -1;
  103921. };
  103922. /**
  103923. * This function set the data for each triangle.
  103924. * Data are position, normals and uvs
  103925. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  103926. * If the tuple already exist, add only their indice
  103927. *
  103928. * @param indicePositionFromObj Integer The index in positions array
  103929. * @param indiceUvsFromObj Integer The index in uvs array
  103930. * @param indiceNormalFromObj Integer The index in normals array
  103931. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  103932. * @param textureVectorFromOBJ Vector3 The value of uvs
  103933. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  103934. */
  103935. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  103936. //Check if this tuple already exists in the list of tuples
  103937. var _index;
  103938. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  103939. _index = isInArrayUV(tuplePosNorm, [
  103940. indicePositionFromObj,
  103941. indiceNormalFromObj,
  103942. indiceUvsFromObj
  103943. ]);
  103944. }
  103945. else {
  103946. _index = isInArray(tuplePosNorm, [
  103947. indicePositionFromObj,
  103948. indiceNormalFromObj
  103949. ]);
  103950. }
  103951. //If it not exists
  103952. if (_index == -1) {
  103953. //Add an new indice.
  103954. //The array of indices is only an array with his length equal to the number of triangles - 1.
  103955. //We add vertices data in this order
  103956. indicesForBabylon.push(wrappedPositionForBabylon.length);
  103957. //Push the position of vertice for Babylon
  103958. //Each element is a BABYLON.Vector3(x,y,z)
  103959. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  103960. //Push the uvs for Babylon
  103961. //Each element is a BABYLON.Vector3(u,v)
  103962. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  103963. //Push the normals for Babylon
  103964. //Each element is a BABYLON.Vector3(x,y,z)
  103965. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  103966. //Add the tuple in the comparison list
  103967. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  103968. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  103969. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  103970. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  103971. }
  103972. else {
  103973. //The tuple already exists
  103974. //Add the index of the already existing tuple
  103975. //At this index we can get the value of position, normal and uvs of vertex
  103976. indicesForBabylon.push(_index);
  103977. }
  103978. };
  103979. /**
  103980. * Transform BABYLON.Vector() object onto 3 digits in an array
  103981. */
  103982. var unwrapData = function () {
  103983. //Every array has the same length
  103984. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  103985. //Push the x, y, z values of each element in the unwrapped array
  103986. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  103987. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  103988. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  103989. }
  103990. // Reset arrays for the next new meshes
  103991. wrappedPositionForBabylon = [];
  103992. wrappedNormalsForBabylon = [];
  103993. wrappedUvsForBabylon = [];
  103994. tuplePosNorm = [];
  103995. curPositionInIndices = 0;
  103996. };
  103997. /**
  103998. * Create triangles from polygons by recursion
  103999. * The best to understand how it works is to draw it in the same time you get the recursion.
  104000. * It is important to notice that a triangle is a polygon
  104001. * We get 4 patterns of face defined in OBJ File :
  104002. * facePattern1 = ["1","2","3","4","5","6"]
  104003. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  104004. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  104005. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  104006. * Each pattern is divided by the same method
  104007. * @param face Array[String] The indices of elements
  104008. * @param v Integer The variable to increment
  104009. */
  104010. var getTriangles = function (face, v) {
  104011. //Work for each element of the array
  104012. if (v + 1 < face.length) {
  104013. //Add on the triangle variable the indexes to obtain triangles
  104014. triangles.push(face[0], face[v], face[v + 1]);
  104015. //Incrementation for recursion
  104016. v += 1;
  104017. //Recursion
  104018. getTriangles(face, v);
  104019. }
  104020. //Result obtained after 2 iterations:
  104021. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  104022. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  104023. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  104024. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  104025. };
  104026. /**
  104027. * Create triangles and push the data for each polygon for the pattern 1
  104028. * In this pattern we get vertice positions
  104029. * @param face
  104030. * @param v
  104031. */
  104032. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  104033. //Get the indices of triangles for each polygon
  104034. getTriangles(face, v);
  104035. //For each element in the triangles array.
  104036. //This var could contains 1 to an infinity of triangles
  104037. for (var k = 0; k < triangles.length; k++) {
  104038. // Set position indice
  104039. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  104040. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  104041. positions[indicePositionFromObj], //Get the vectors data
  104042. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  104043. );
  104044. }
  104045. //Reset variable for the next line
  104046. triangles = [];
  104047. };
  104048. /**
  104049. * Create triangles and push the data for each polygon for the pattern 2
  104050. * In this pattern we get vertice positions and uvsu
  104051. * @param face
  104052. * @param v
  104053. */
  104054. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  104055. //Get the indices of triangles for each polygon
  104056. getTriangles(face, v);
  104057. for (var k = 0; k < triangles.length; k++) {
  104058. //triangle[k] = "1/1"
  104059. //Split the data for getting position and uv
  104060. var point = triangles[k].split("/"); // ["1", "1"]
  104061. //Set position indice
  104062. var indicePositionFromObj = parseInt(point[0]) - 1;
  104063. //Set uv indice
  104064. var indiceUvsFromObj = parseInt(point[1]) - 1;
  104065. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  104066. positions[indicePositionFromObj], //Get the values for each element
  104067. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  104068. );
  104069. }
  104070. //Reset variable for the next line
  104071. triangles = [];
  104072. };
  104073. /**
  104074. * Create triangles and push the data for each polygon for the pattern 3
  104075. * In this pattern we get vertice positions, uvs and normals
  104076. * @param face
  104077. * @param v
  104078. */
  104079. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  104080. //Get the indices of triangles for each polygon
  104081. getTriangles(face, v);
  104082. for (var k = 0; k < triangles.length; k++) {
  104083. //triangle[k] = "1/1/1"
  104084. //Split the data for getting position, uv, and normals
  104085. var point = triangles[k].split("/"); // ["1", "1", "1"]
  104086. // Set position indice
  104087. var indicePositionFromObj = parseInt(point[0]) - 1;
  104088. // Set uv indice
  104089. var indiceUvsFromObj = parseInt(point[1]) - 1;
  104090. // Set normal indice
  104091. var indiceNormalFromObj = parseInt(point[2]) - 1;
  104092. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  104093. );
  104094. }
  104095. //Reset variable for the next line
  104096. triangles = [];
  104097. };
  104098. /**
  104099. * Create triangles and push the data for each polygon for the pattern 4
  104100. * In this pattern we get vertice positions and normals
  104101. * @param face
  104102. * @param v
  104103. */
  104104. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  104105. getTriangles(face, v);
  104106. for (var k = 0; k < triangles.length; k++) {
  104107. //triangle[k] = "1//1"
  104108. //Split the data for getting position and normals
  104109. var point = triangles[k].split("//"); // ["1", "1"]
  104110. // We check indices, and normals
  104111. var indicePositionFromObj = parseInt(point[0]) - 1;
  104112. var indiceNormalFromObj = parseInt(point[1]) - 1;
  104113. setData(indicePositionFromObj, 1, //Default value for uv
  104114. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  104115. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  104116. }
  104117. //Reset variable for the next line
  104118. triangles = [];
  104119. };
  104120. var addPreviousObjMesh = function () {
  104121. //Check if it is not the first mesh. Otherwise we don't have data.
  104122. if (meshesFromObj.length > 0) {
  104123. //Get the previous mesh for applying the data about the faces
  104124. //=> in obj file, faces definition append after the name of the mesh
  104125. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  104126. //Set the data into Array for the mesh
  104127. unwrapData();
  104128. // Reverse tab. Otherwise face are displayed in the wrong sens
  104129. indicesForBabylon.reverse();
  104130. //Set the information for the mesh
  104131. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  104132. handledMesh.indices = indicesForBabylon.slice();
  104133. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  104134. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  104135. handledMesh.uvs = unwrappedUVForBabylon.slice();
  104136. //Reset the array for the next mesh
  104137. indicesForBabylon = [];
  104138. unwrappedPositionsForBabylon = [];
  104139. unwrappedNormalsForBabylon = [];
  104140. unwrappedUVForBabylon = [];
  104141. }
  104142. };
  104143. //Main function
  104144. //Split the file into lines
  104145. var lines = data.split('\n');
  104146. //Look at each line
  104147. for (var i = 0; i < lines.length; i++) {
  104148. var line = lines[i].trim();
  104149. var result;
  104150. //Comment or newLine
  104151. if (line.length === 0 || line.charAt(0) === '#') {
  104152. continue;
  104153. //Get information about one position possible for the vertices
  104154. }
  104155. else if ((result = this.vertexPattern.exec(line)) !== null) {
  104156. //Create a Vector3 with the position x, y, z
  104157. //Value of result:
  104158. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  104159. //Add the Vector in the list of positions
  104160. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  104161. }
  104162. else if ((result = this.normalPattern.exec(line)) !== null) {
  104163. //Create a Vector3 with the normals x, y, z
  104164. //Value of result
  104165. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  104166. //Add the Vector in the list of normals
  104167. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  104168. }
  104169. else if ((result = this.uvPattern.exec(line)) !== null) {
  104170. //Create a Vector2 with the normals u, v
  104171. //Value of result
  104172. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  104173. //Add the Vector in the list of uvs
  104174. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  104175. //Identify patterns of faces
  104176. //Face could be defined in different type of pattern
  104177. }
  104178. else if ((result = this.facePattern3.exec(line)) !== null) {
  104179. //Value of result:
  104180. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  104181. //Set the data for this face
  104182. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  104183. 1);
  104184. }
  104185. else if ((result = this.facePattern4.exec(line)) !== null) {
  104186. //Value of result:
  104187. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  104188. //Set the data for this face
  104189. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  104190. 1);
  104191. }
  104192. else if ((result = this.facePattern2.exec(line)) !== null) {
  104193. //Value of result:
  104194. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  104195. //Set the data for this face
  104196. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  104197. 1);
  104198. }
  104199. else if ((result = this.facePattern1.exec(line)) !== null) {
  104200. //Value of result
  104201. //["f 1 2 3", "1 2 3"...]
  104202. //Set the data for this face
  104203. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  104204. 1);
  104205. //Define a mesh or an object
  104206. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  104207. }
  104208. else if (this.group.test(line) || this.obj.test(line)) {
  104209. //Create a new mesh corresponding to the name of the group.
  104210. //Definition of the mesh
  104211. var objMesh =
  104212. //Set the name of the current obj mesh
  104213. {
  104214. name: line.substring(2).trim(),
  104215. indices: undefined,
  104216. positions: undefined,
  104217. normals: undefined,
  104218. uvs: undefined,
  104219. materialName: ""
  104220. };
  104221. addPreviousObjMesh();
  104222. //Push the last mesh created with only the name
  104223. meshesFromObj.push(objMesh);
  104224. //Set this variable to indicate that now meshesFromObj has objects defined inside
  104225. hasMeshes = true;
  104226. isFirstMaterial = true;
  104227. increment = 1;
  104228. //Keyword for applying a material
  104229. }
  104230. else if (this.usemtl.test(line)) {
  104231. //Get the name of the material
  104232. materialNameFromObj = line.substring(7).trim();
  104233. //If this new material is in the same mesh
  104234. if (!isFirstMaterial) {
  104235. //Set the data for the previous mesh
  104236. addPreviousObjMesh();
  104237. //Create a new mesh
  104238. var objMesh =
  104239. //Set the name of the current obj mesh
  104240. {
  104241. name: objMeshName + "_mm" + increment.toString(),
  104242. indices: undefined,
  104243. positions: undefined,
  104244. normals: undefined,
  104245. uvs: undefined,
  104246. materialName: materialNameFromObj
  104247. };
  104248. increment++;
  104249. //If meshes are already defined
  104250. meshesFromObj.push(objMesh);
  104251. }
  104252. //Set the material name if the previous line define a mesh
  104253. if (hasMeshes && isFirstMaterial) {
  104254. //Set the material name to the previous mesh (1 material per mesh)
  104255. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  104256. isFirstMaterial = false;
  104257. }
  104258. //Keyword for loading the mtl file
  104259. }
  104260. else if (this.mtllib.test(line)) {
  104261. //Get the name of mtl file
  104262. fileToLoad = line.substring(7).trim();
  104263. //Apply smoothing
  104264. }
  104265. else if (this.smooth.test(line)) {
  104266. // smooth shading => apply smoothing
  104267. //Toda y I don't know it work with babylon and with obj.
  104268. //With the obj file an integer is set
  104269. }
  104270. else {
  104271. //If there is another possibility
  104272. console.log("Unhandled expression at line : " + line);
  104273. }
  104274. }
  104275. //At the end of the file, add the last mesh into the meshesFromObj array
  104276. if (hasMeshes) {
  104277. //Set the data for the last mesh
  104278. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  104279. //Reverse indices for displaying faces in the good sens
  104280. indicesForBabylon.reverse();
  104281. //Get the good array
  104282. unwrapData();
  104283. //Set array
  104284. handledMesh.indices = indicesForBabylon;
  104285. handledMesh.positions = unwrappedPositionsForBabylon;
  104286. handledMesh.normals = unwrappedNormalsForBabylon;
  104287. handledMesh.uvs = unwrappedUVForBabylon;
  104288. }
  104289. //If any o or g keyword found, create a mesj with a random id
  104290. if (!hasMeshes) {
  104291. // reverse tab of indices
  104292. indicesForBabylon.reverse();
  104293. //Get positions normals uvs
  104294. unwrapData();
  104295. //Set data for one mesh
  104296. meshesFromObj.push({
  104297. name: BABYLON.Geometry.RandomId(),
  104298. indices: indicesForBabylon,
  104299. positions: unwrappedPositionsForBabylon,
  104300. normals: unwrappedNormalsForBabylon,
  104301. uvs: unwrappedUVForBabylon,
  104302. materialName: materialNameFromObj
  104303. });
  104304. }
  104305. //Create a BABYLON.Mesh list
  104306. var babylonMeshesArray = []; //The mesh for babylon
  104307. var materialToUse = new Array();
  104308. //Set data for each mesh
  104309. for (var j = 0; j < meshesFromObj.length; j++) {
  104310. //check meshesNames (stlFileLoader)
  104311. if (meshesNames && meshesFromObj[j].name) {
  104312. if (meshesNames instanceof Array) {
  104313. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  104314. continue;
  104315. }
  104316. }
  104317. else {
  104318. if (meshesFromObj[j].name !== meshesNames) {
  104319. continue;
  104320. }
  104321. }
  104322. }
  104323. //Get the current mesh
  104324. //Set the data with VertexBuffer for each mesh
  104325. handledMesh = meshesFromObj[j];
  104326. //Create a BABYLON.Mesh with the name of the obj mesh
  104327. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  104328. //Push the name of the material to an array
  104329. //This is indispensable for the importMesh function
  104330. materialToUse.push(meshesFromObj[j].materialName);
  104331. var vertexData = new BABYLON.VertexData(); //The container for the values
  104332. //Set the data for the babylonMesh
  104333. vertexData.positions = handledMesh.positions;
  104334. vertexData.normals = handledMesh.normals;
  104335. vertexData.uvs = handledMesh.uvs;
  104336. vertexData.indices = handledMesh.indices;
  104337. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  104338. vertexData.applyToMesh(babylonMesh);
  104339. //Push the mesh into an array
  104340. babylonMeshesArray.push(babylonMesh);
  104341. }
  104342. //load the materials
  104343. //Check if we have a file to load
  104344. if (fileToLoad !== "") {
  104345. //Load the file synchronously
  104346. this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  104347. //Create materials thanks MTLLoader function
  104348. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  104349. //Look at each material loaded in the mtl file
  104350. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  104351. //Three variables to get all meshes with the same material
  104352. var startIndex = 0;
  104353. var _indices = [];
  104354. var _index;
  104355. //The material from MTL file is used in the meshes loaded
  104356. //Push the indice in an array
  104357. //Check if the material is not used for another mesh
  104358. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  104359. _indices.push(_index);
  104360. startIndex = _index + 1;
  104361. }
  104362. //If the material is not used dispose it
  104363. if (_index == -1 && _indices.length == 0) {
  104364. //If the material is not needed, remove it
  104365. materialsFromMTLFile.materials[n].dispose();
  104366. }
  104367. else {
  104368. for (var o = 0; o < _indices.length; o++) {
  104369. //Apply the material to the BABYLON.Mesh for each mesh with the material
  104370. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  104371. }
  104372. }
  104373. }
  104374. });
  104375. }
  104376. //Return an array with all BABYLON.Mesh
  104377. return babylonMeshesArray;
  104378. };
  104379. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  104380. return OBJFileLoader;
  104381. }());
  104382. BABYLON.OBJFileLoader = OBJFileLoader;
  104383. if (BABYLON.SceneLoader) {
  104384. //Add this loader into the register plugin
  104385. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  104386. }
  104387. })(BABYLON || (BABYLON = {}));
  104388. //# sourceMappingURL=babylon.objFileLoader.js.map
  104389. var BABYLON;
  104390. (function (BABYLON) {
  104391. var GLTFLoaderCoordinateSystemMode;
  104392. (function (GLTFLoaderCoordinateSystemMode) {
  104393. /**
  104394. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  104395. */
  104396. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  104397. /**
  104398. * Sets the useRightHandedSystem flag on the scene.
  104399. */
  104400. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  104401. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  104402. var GLTFLoaderAnimationStartMode;
  104403. (function (GLTFLoaderAnimationStartMode) {
  104404. /**
  104405. * No animation will start.
  104406. */
  104407. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  104408. /**
  104409. * The first animation will start.
  104410. */
  104411. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  104412. /**
  104413. * All animations will start.
  104414. */
  104415. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  104416. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  104417. var GLTFLoaderState;
  104418. (function (GLTFLoaderState) {
  104419. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  104420. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  104421. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  104422. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  104423. var GLTFFileLoader = /** @class */ (function () {
  104424. function GLTFFileLoader() {
  104425. // #region Common options
  104426. /**
  104427. * Raised when the asset has been parsed.
  104428. * The data.json property stores the glTF JSON.
  104429. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  104430. */
  104431. this.onParsedObservable = new BABYLON.Observable();
  104432. // #endregion
  104433. // #region V2 options
  104434. /**
  104435. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  104436. */
  104437. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  104438. /**
  104439. * The animation start mode (NONE, FIRST, ALL).
  104440. */
  104441. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  104442. /**
  104443. * Set to true to compile materials before raising the success callback.
  104444. */
  104445. this.compileMaterials = false;
  104446. /**
  104447. * Set to true to also compile materials with clip planes.
  104448. */
  104449. this.useClipPlane = false;
  104450. /**
  104451. * Set to true to compile shadow generators before raising the success callback.
  104452. */
  104453. this.compileShadowGenerators = false;
  104454. /**
  104455. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  104456. */
  104457. this.onMeshLoadedObservable = new BABYLON.Observable();
  104458. /**
  104459. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  104460. */
  104461. this.onTextureLoadedObservable = new BABYLON.Observable();
  104462. /**
  104463. * Raised when the loader creates a material after parsing the glTF properties of the material.
  104464. */
  104465. this.onMaterialLoadedObservable = new BABYLON.Observable();
  104466. /**
  104467. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  104468. * For assets with LODs, raised when all of the LODs are complete.
  104469. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  104470. */
  104471. this.onCompleteObservable = new BABYLON.Observable();
  104472. /**
  104473. * Raised when the loader is disposed.
  104474. */
  104475. this.onDisposeObservable = new BABYLON.Observable();
  104476. /**
  104477. * Raised after a loader extension is created.
  104478. * Set additional options for a loader extension in this event.
  104479. */
  104480. this.onExtensionLoadedObservable = new BABYLON.Observable();
  104481. // #endregion
  104482. this._loader = null;
  104483. this.name = "gltf";
  104484. this.extensions = {
  104485. ".gltf": { isBinary: false },
  104486. ".glb": { isBinary: true }
  104487. };
  104488. }
  104489. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  104490. set: function (callback) {
  104491. if (this._onParsedObserver) {
  104492. this.onParsedObservable.remove(this._onParsedObserver);
  104493. }
  104494. this._onParsedObserver = this.onParsedObservable.add(callback);
  104495. },
  104496. enumerable: true,
  104497. configurable: true
  104498. });
  104499. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  104500. set: function (callback) {
  104501. if (this._onMeshLoadedObserver) {
  104502. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  104503. }
  104504. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  104505. },
  104506. enumerable: true,
  104507. configurable: true
  104508. });
  104509. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  104510. set: function (callback) {
  104511. if (this._onTextureLoadedObserver) {
  104512. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  104513. }
  104514. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  104515. },
  104516. enumerable: true,
  104517. configurable: true
  104518. });
  104519. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  104520. set: function (callback) {
  104521. if (this._onMaterialLoadedObserver) {
  104522. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  104523. }
  104524. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  104525. },
  104526. enumerable: true,
  104527. configurable: true
  104528. });
  104529. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  104530. set: function (callback) {
  104531. if (this._onCompleteObserver) {
  104532. this.onCompleteObservable.remove(this._onCompleteObserver);
  104533. }
  104534. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  104535. },
  104536. enumerable: true,
  104537. configurable: true
  104538. });
  104539. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  104540. set: function (callback) {
  104541. if (this._onDisposeObserver) {
  104542. this.onDisposeObservable.remove(this._onDisposeObserver);
  104543. }
  104544. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  104545. },
  104546. enumerable: true,
  104547. configurable: true
  104548. });
  104549. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  104550. set: function (callback) {
  104551. if (this._onExtensionLoadedObserver) {
  104552. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  104553. }
  104554. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  104555. },
  104556. enumerable: true,
  104557. configurable: true
  104558. });
  104559. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  104560. /**
  104561. * The loader state or null if not active.
  104562. */
  104563. get: function () {
  104564. return this._loader ? this._loader.state : null;
  104565. },
  104566. enumerable: true,
  104567. configurable: true
  104568. });
  104569. /**
  104570. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  104571. */
  104572. GLTFFileLoader.prototype.dispose = function () {
  104573. if (this._loader) {
  104574. this._loader.dispose();
  104575. this._loader = null;
  104576. }
  104577. this.onMeshLoadedObservable.clear();
  104578. this.onTextureLoadedObservable.clear();
  104579. this.onMaterialLoadedObservable.clear();
  104580. this.onDisposeObservable.notifyObservers(this);
  104581. this.onDisposeObservable.clear();
  104582. };
  104583. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  104584. var _this = this;
  104585. return Promise.resolve().then(function () {
  104586. var loaderData = _this._parse(data);
  104587. _this._loader = _this._getLoader(loaderData);
  104588. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  104589. });
  104590. };
  104591. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  104592. var _this = this;
  104593. return Promise.resolve().then(function () {
  104594. var loaderData = _this._parse(data);
  104595. _this._loader = _this._getLoader(loaderData);
  104596. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  104597. });
  104598. };
  104599. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  104600. var _this = this;
  104601. return Promise.resolve().then(function () {
  104602. var loaderData = _this._parse(data);
  104603. _this._loader = _this._getLoader(loaderData);
  104604. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  104605. var container = new BABYLON.AssetContainer(scene);
  104606. Array.prototype.push.apply(container.meshes, result.meshes);
  104607. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  104608. Array.prototype.push.apply(container.skeletons, result.skeletons);
  104609. container.removeAllFromScene();
  104610. return container;
  104611. });
  104612. });
  104613. };
  104614. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  104615. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  104616. };
  104617. GLTFFileLoader.prototype.createPlugin = function () {
  104618. return new GLTFFileLoader();
  104619. };
  104620. GLTFFileLoader.prototype._parse = function (data) {
  104621. var parsedData;
  104622. if (data instanceof ArrayBuffer) {
  104623. parsedData = GLTFFileLoader._parseBinary(data);
  104624. }
  104625. else {
  104626. parsedData = {
  104627. json: JSON.parse(data),
  104628. bin: null
  104629. };
  104630. }
  104631. this.onParsedObservable.notifyObservers(parsedData);
  104632. this.onParsedObservable.clear();
  104633. return parsedData;
  104634. };
  104635. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  104636. var _this = this;
  104637. var loaderVersion = { major: 2, minor: 0 };
  104638. var asset = loaderData.json.asset || {};
  104639. var version = GLTFFileLoader._parseVersion(asset.version);
  104640. if (!version) {
  104641. throw new Error("Invalid version: " + asset.version);
  104642. }
  104643. if (asset.minVersion !== undefined) {
  104644. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  104645. if (!minVersion) {
  104646. throw new Error("Invalid minimum version: " + asset.minVersion);
  104647. }
  104648. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  104649. throw new Error("Incompatible minimum version: " + asset.minVersion);
  104650. }
  104651. }
  104652. var createLoaders = {
  104653. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  104654. 2: GLTFFileLoader.CreateGLTFLoaderV2
  104655. };
  104656. var createLoader = createLoaders[version.major];
  104657. if (!createLoader) {
  104658. throw new Error("Unsupported version: " + asset.version);
  104659. }
  104660. var loader = createLoader();
  104661. loader.coordinateSystemMode = this.coordinateSystemMode;
  104662. loader.animationStartMode = this.animationStartMode;
  104663. loader.compileMaterials = this.compileMaterials;
  104664. loader.useClipPlane = this.useClipPlane;
  104665. loader.compileShadowGenerators = this.compileShadowGenerators;
  104666. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  104667. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  104668. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  104669. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  104670. loader.onCompleteObservable.add(function () {
  104671. _this.onMeshLoadedObservable.clear();
  104672. _this.onTextureLoadedObservable.clear();
  104673. _this.onMaterialLoadedObservable.clear();
  104674. _this.onCompleteObservable.notifyObservers(_this);
  104675. _this.onCompleteObservable.clear();
  104676. });
  104677. return loader;
  104678. };
  104679. GLTFFileLoader._parseBinary = function (data) {
  104680. var Binary = {
  104681. Magic: 0x46546C67
  104682. };
  104683. var binaryReader = new BinaryReader(data);
  104684. var magic = binaryReader.readUint32();
  104685. if (magic !== Binary.Magic) {
  104686. throw new Error("Unexpected magic: " + magic);
  104687. }
  104688. var version = binaryReader.readUint32();
  104689. switch (version) {
  104690. case 1: return GLTFFileLoader._parseV1(binaryReader);
  104691. case 2: return GLTFFileLoader._parseV2(binaryReader);
  104692. }
  104693. throw new Error("Unsupported version: " + version);
  104694. };
  104695. GLTFFileLoader._parseV1 = function (binaryReader) {
  104696. var ContentFormat = {
  104697. JSON: 0
  104698. };
  104699. var length = binaryReader.readUint32();
  104700. if (length != binaryReader.getLength()) {
  104701. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  104702. }
  104703. var contentLength = binaryReader.readUint32();
  104704. var contentFormat = binaryReader.readUint32();
  104705. var content;
  104706. switch (contentFormat) {
  104707. case ContentFormat.JSON: {
  104708. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  104709. break;
  104710. }
  104711. default: {
  104712. throw new Error("Unexpected content format: " + contentFormat);
  104713. }
  104714. }
  104715. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  104716. var body = binaryReader.readUint8Array(bytesRemaining);
  104717. return {
  104718. json: content,
  104719. bin: body
  104720. };
  104721. };
  104722. GLTFFileLoader._parseV2 = function (binaryReader) {
  104723. var ChunkFormat = {
  104724. JSON: 0x4E4F534A,
  104725. BIN: 0x004E4942
  104726. };
  104727. var length = binaryReader.readUint32();
  104728. if (length !== binaryReader.getLength()) {
  104729. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  104730. }
  104731. // JSON chunk
  104732. var chunkLength = binaryReader.readUint32();
  104733. var chunkFormat = binaryReader.readUint32();
  104734. if (chunkFormat !== ChunkFormat.JSON) {
  104735. throw new Error("First chunk format is not JSON");
  104736. }
  104737. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  104738. // Look for BIN chunk
  104739. var bin = null;
  104740. while (binaryReader.getPosition() < binaryReader.getLength()) {
  104741. var chunkLength_1 = binaryReader.readUint32();
  104742. var chunkFormat_1 = binaryReader.readUint32();
  104743. switch (chunkFormat_1) {
  104744. case ChunkFormat.JSON: {
  104745. throw new Error("Unexpected JSON chunk");
  104746. }
  104747. case ChunkFormat.BIN: {
  104748. bin = binaryReader.readUint8Array(chunkLength_1);
  104749. break;
  104750. }
  104751. default: {
  104752. // ignore unrecognized chunkFormat
  104753. binaryReader.skipBytes(chunkLength_1);
  104754. break;
  104755. }
  104756. }
  104757. }
  104758. return {
  104759. json: json,
  104760. bin: bin
  104761. };
  104762. };
  104763. GLTFFileLoader._parseVersion = function (version) {
  104764. if (version === "1.0" || version === "1.0.1") {
  104765. return {
  104766. major: 1,
  104767. minor: 0
  104768. };
  104769. }
  104770. var match = (version + "").match(/^(\d+)\.(\d+)/);
  104771. if (!match) {
  104772. return null;
  104773. }
  104774. return {
  104775. major: parseInt(match[1]),
  104776. minor: parseInt(match[2])
  104777. };
  104778. };
  104779. GLTFFileLoader._compareVersion = function (a, b) {
  104780. if (a.major > b.major)
  104781. return 1;
  104782. if (a.major < b.major)
  104783. return -1;
  104784. if (a.minor > b.minor)
  104785. return 1;
  104786. if (a.minor < b.minor)
  104787. return -1;
  104788. return 0;
  104789. };
  104790. GLTFFileLoader._decodeBufferToText = function (buffer) {
  104791. var result = "";
  104792. var length = buffer.byteLength;
  104793. for (var i = 0; i < length; i++) {
  104794. result += String.fromCharCode(buffer[i]);
  104795. }
  104796. return result;
  104797. };
  104798. // #endregion
  104799. // #region V1 options
  104800. GLTFFileLoader.IncrementalLoading = true;
  104801. GLTFFileLoader.HomogeneousCoordinates = false;
  104802. return GLTFFileLoader;
  104803. }());
  104804. BABYLON.GLTFFileLoader = GLTFFileLoader;
  104805. var BinaryReader = /** @class */ (function () {
  104806. function BinaryReader(arrayBuffer) {
  104807. this._arrayBuffer = arrayBuffer;
  104808. this._dataView = new DataView(arrayBuffer);
  104809. this._byteOffset = 0;
  104810. }
  104811. BinaryReader.prototype.getPosition = function () {
  104812. return this._byteOffset;
  104813. };
  104814. BinaryReader.prototype.getLength = function () {
  104815. return this._arrayBuffer.byteLength;
  104816. };
  104817. BinaryReader.prototype.readUint32 = function () {
  104818. var value = this._dataView.getUint32(this._byteOffset, true);
  104819. this._byteOffset += 4;
  104820. return value;
  104821. };
  104822. BinaryReader.prototype.readUint8Array = function (length) {
  104823. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  104824. this._byteOffset += length;
  104825. return value;
  104826. };
  104827. BinaryReader.prototype.skipBytes = function (length) {
  104828. this._byteOffset += length;
  104829. };
  104830. return BinaryReader;
  104831. }());
  104832. if (BABYLON.SceneLoader) {
  104833. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  104834. }
  104835. })(BABYLON || (BABYLON = {}));
  104836. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  104837. var BABYLON;
  104838. (function (BABYLON) {
  104839. var GLTF1;
  104840. (function (GLTF1) {
  104841. /**
  104842. * Enums
  104843. */
  104844. var EComponentType;
  104845. (function (EComponentType) {
  104846. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  104847. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  104848. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  104849. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  104850. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  104851. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  104852. var EShaderType;
  104853. (function (EShaderType) {
  104854. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  104855. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  104856. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  104857. var EParameterType;
  104858. (function (EParameterType) {
  104859. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  104860. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  104861. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  104862. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  104863. EParameterType[EParameterType["INT"] = 5124] = "INT";
  104864. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  104865. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  104866. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  104867. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  104868. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  104869. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  104870. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  104871. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  104872. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  104873. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  104874. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  104875. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  104876. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  104877. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  104878. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  104879. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  104880. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  104881. var ETextureWrapMode;
  104882. (function (ETextureWrapMode) {
  104883. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  104884. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  104885. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  104886. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  104887. var ETextureFilterType;
  104888. (function (ETextureFilterType) {
  104889. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  104890. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  104891. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  104892. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  104893. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  104894. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  104895. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  104896. var ETextureFormat;
  104897. (function (ETextureFormat) {
  104898. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  104899. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  104900. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  104901. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  104902. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  104903. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  104904. var ECullingType;
  104905. (function (ECullingType) {
  104906. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  104907. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  104908. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  104909. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  104910. var EBlendingFunction;
  104911. (function (EBlendingFunction) {
  104912. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  104913. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  104914. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  104915. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  104916. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  104917. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  104918. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  104919. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  104920. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  104921. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  104922. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  104923. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  104924. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  104925. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  104926. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  104927. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  104928. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  104929. })(BABYLON || (BABYLON = {}));
  104930. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  104931. var BABYLON;
  104932. (function (BABYLON) {
  104933. var GLTF1;
  104934. (function (GLTF1) {
  104935. /**
  104936. * Tokenizer. Used for shaders compatibility
  104937. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  104938. */
  104939. var ETokenType;
  104940. (function (ETokenType) {
  104941. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  104942. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  104943. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  104944. })(ETokenType || (ETokenType = {}));
  104945. var Tokenizer = /** @class */ (function () {
  104946. function Tokenizer(toParse) {
  104947. this._pos = 0;
  104948. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  104949. this._toParse = toParse;
  104950. this._maxPos = toParse.length;
  104951. }
  104952. Tokenizer.prototype.getNextToken = function () {
  104953. if (this.isEnd())
  104954. return ETokenType.END_OF_INPUT;
  104955. this.currentString = this.read();
  104956. this.currentToken = ETokenType.UNKNOWN;
  104957. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  104958. this.currentToken = ETokenType.IDENTIFIER;
  104959. this.currentIdentifier = this.currentString;
  104960. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  104961. this.currentIdentifier += this.currentString;
  104962. this.forward();
  104963. }
  104964. }
  104965. return this.currentToken;
  104966. };
  104967. Tokenizer.prototype.peek = function () {
  104968. return this._toParse[this._pos];
  104969. };
  104970. Tokenizer.prototype.read = function () {
  104971. return this._toParse[this._pos++];
  104972. };
  104973. Tokenizer.prototype.forward = function () {
  104974. this._pos++;
  104975. };
  104976. Tokenizer.prototype.isEnd = function () {
  104977. return this._pos >= this._maxPos;
  104978. };
  104979. return Tokenizer;
  104980. }());
  104981. /**
  104982. * Values
  104983. */
  104984. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  104985. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  104986. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  104987. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  104988. /**
  104989. * Parse
  104990. */
  104991. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  104992. for (var buf in parsedBuffers) {
  104993. var parsedBuffer = parsedBuffers[buf];
  104994. gltfRuntime.buffers[buf] = parsedBuffer;
  104995. gltfRuntime.buffersCount++;
  104996. }
  104997. };
  104998. var parseShaders = function (parsedShaders, gltfRuntime) {
  104999. for (var sha in parsedShaders) {
  105000. var parsedShader = parsedShaders[sha];
  105001. gltfRuntime.shaders[sha] = parsedShader;
  105002. gltfRuntime.shaderscount++;
  105003. }
  105004. };
  105005. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  105006. for (var object in parsedObjects) {
  105007. var parsedObject = parsedObjects[object];
  105008. gltfRuntime[runtimeProperty][object] = parsedObject;
  105009. }
  105010. };
  105011. /**
  105012. * Utils
  105013. */
  105014. var normalizeUVs = function (buffer) {
  105015. if (!buffer) {
  105016. return;
  105017. }
  105018. for (var i = 0; i < buffer.length / 2; i++) {
  105019. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  105020. }
  105021. };
  105022. var getAttribute = function (attributeParameter) {
  105023. if (attributeParameter.semantic === "NORMAL") {
  105024. return "normal";
  105025. }
  105026. else if (attributeParameter.semantic === "POSITION") {
  105027. return "position";
  105028. }
  105029. else if (attributeParameter.semantic === "JOINT") {
  105030. return "matricesIndices";
  105031. }
  105032. else if (attributeParameter.semantic === "WEIGHT") {
  105033. return "matricesWeights";
  105034. }
  105035. else if (attributeParameter.semantic === "COLOR") {
  105036. return "color";
  105037. }
  105038. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  105039. var channel = Number(attributeParameter.semantic.split("_")[1]);
  105040. return "uv" + (channel === 0 ? "" : channel + 1);
  105041. }
  105042. return null;
  105043. };
  105044. /**
  105045. * Loads and creates animations
  105046. */
  105047. var loadAnimations = function (gltfRuntime) {
  105048. for (var anim in gltfRuntime.animations) {
  105049. var animation = gltfRuntime.animations[anim];
  105050. if (!animation.channels || !animation.samplers) {
  105051. continue;
  105052. }
  105053. var lastAnimation = null;
  105054. for (var i = 0; i < animation.channels.length; i++) {
  105055. // Get parameters and load buffers
  105056. var channel = animation.channels[i];
  105057. var sampler = animation.samplers[channel.sampler];
  105058. if (!sampler) {
  105059. continue;
  105060. }
  105061. var inputData = null;
  105062. var outputData = null;
  105063. if (animation.parameters) {
  105064. inputData = animation.parameters[sampler.input];
  105065. outputData = animation.parameters[sampler.output];
  105066. }
  105067. else {
  105068. inputData = sampler.input;
  105069. outputData = sampler.output;
  105070. }
  105071. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  105072. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  105073. var targetID = channel.target.id;
  105074. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  105075. if (targetNode === null) {
  105076. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  105077. }
  105078. if (targetNode === null) {
  105079. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  105080. continue;
  105081. }
  105082. var isBone = targetNode instanceof BABYLON.Bone;
  105083. // Get target path (position, rotation or scaling)
  105084. var targetPath = channel.target.path;
  105085. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  105086. if (targetPathIndex !== -1) {
  105087. targetPath = babylonAnimationPaths[targetPathIndex];
  105088. }
  105089. // Determine animation type
  105090. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  105091. if (!isBone) {
  105092. if (targetPath === "rotationQuaternion") {
  105093. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  105094. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  105095. }
  105096. else {
  105097. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  105098. }
  105099. }
  105100. // Create animation and key frames
  105101. var babylonAnimation = null;
  105102. var keys = [];
  105103. var arrayOffset = 0;
  105104. var modifyKey = false;
  105105. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  105106. babylonAnimation = lastAnimation;
  105107. modifyKey = true;
  105108. }
  105109. if (!modifyKey) {
  105110. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  105111. }
  105112. // For each frame
  105113. for (var j = 0; j < bufferInput.length; j++) {
  105114. var value = null;
  105115. if (targetPath === "rotationQuaternion") {
  105116. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  105117. arrayOffset += 4;
  105118. }
  105119. else {
  105120. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  105121. arrayOffset += 3;
  105122. }
  105123. if (isBone) {
  105124. var bone = targetNode;
  105125. var translation = BABYLON.Vector3.Zero();
  105126. var rotationQuaternion = new BABYLON.Quaternion();
  105127. var scaling = BABYLON.Vector3.Zero();
  105128. // Warning on decompose
  105129. var mat = bone.getBaseMatrix();
  105130. if (modifyKey && lastAnimation) {
  105131. mat = lastAnimation.getKeys()[j].value;
  105132. }
  105133. mat.decompose(scaling, rotationQuaternion, translation);
  105134. if (targetPath === "position") {
  105135. translation = value;
  105136. }
  105137. else if (targetPath === "rotationQuaternion") {
  105138. rotationQuaternion = value;
  105139. }
  105140. else {
  105141. scaling = value;
  105142. }
  105143. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  105144. }
  105145. if (!modifyKey) {
  105146. keys.push({
  105147. frame: bufferInput[j],
  105148. value: value
  105149. });
  105150. }
  105151. else if (lastAnimation) {
  105152. lastAnimation.getKeys()[j].value = value;
  105153. }
  105154. }
  105155. // Finish
  105156. if (!modifyKey && babylonAnimation) {
  105157. babylonAnimation.setKeys(keys);
  105158. targetNode.animations.push(babylonAnimation);
  105159. }
  105160. lastAnimation = babylonAnimation;
  105161. gltfRuntime.scene.stopAnimation(targetNode);
  105162. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  105163. }
  105164. }
  105165. };
  105166. /**
  105167. * Returns the bones transformation matrix
  105168. */
  105169. var configureBoneTransformation = function (node) {
  105170. var mat = null;
  105171. if (node.translation || node.rotation || node.scale) {
  105172. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  105173. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  105174. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  105175. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  105176. }
  105177. else {
  105178. mat = BABYLON.Matrix.FromArray(node.matrix);
  105179. }
  105180. return mat;
  105181. };
  105182. /**
  105183. * Returns the parent bone
  105184. */
  105185. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  105186. // Try to find
  105187. for (var i = 0; i < newSkeleton.bones.length; i++) {
  105188. if (newSkeleton.bones[i].name === jointName) {
  105189. return newSkeleton.bones[i];
  105190. }
  105191. }
  105192. // Not found, search in gltf nodes
  105193. var nodes = gltfRuntime.nodes;
  105194. for (var nde in nodes) {
  105195. var node = nodes[nde];
  105196. if (!node.jointName) {
  105197. continue;
  105198. }
  105199. var children = node.children;
  105200. for (var i = 0; i < children.length; i++) {
  105201. var child = gltfRuntime.nodes[children[i]];
  105202. if (!child.jointName) {
  105203. continue;
  105204. }
  105205. if (child.jointName === jointName) {
  105206. var mat = configureBoneTransformation(node);
  105207. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  105208. bone.id = nde;
  105209. return bone;
  105210. }
  105211. }
  105212. }
  105213. return null;
  105214. };
  105215. /**
  105216. * Returns the appropriate root node
  105217. */
  105218. var getNodeToRoot = function (nodesToRoot, id) {
  105219. for (var i = 0; i < nodesToRoot.length; i++) {
  105220. var nodeToRoot = nodesToRoot[i];
  105221. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  105222. var child = nodeToRoot.node.children[j];
  105223. if (child === id) {
  105224. return nodeToRoot.bone;
  105225. }
  105226. }
  105227. }
  105228. return null;
  105229. };
  105230. /**
  105231. * Returns the node with the joint name
  105232. */
  105233. var getJointNode = function (gltfRuntime, jointName) {
  105234. var nodes = gltfRuntime.nodes;
  105235. var node = nodes[jointName];
  105236. if (node) {
  105237. return {
  105238. node: node,
  105239. id: jointName
  105240. };
  105241. }
  105242. for (var nde in nodes) {
  105243. node = nodes[nde];
  105244. if (node.jointName === jointName) {
  105245. return {
  105246. node: node,
  105247. id: nde
  105248. };
  105249. }
  105250. }
  105251. return null;
  105252. };
  105253. /**
  105254. * Checks if a nodes is in joints
  105255. */
  105256. var nodeIsInJoints = function (skins, id) {
  105257. for (var i = 0; i < skins.jointNames.length; i++) {
  105258. if (skins.jointNames[i] === id) {
  105259. return true;
  105260. }
  105261. }
  105262. return false;
  105263. };
  105264. /**
  105265. * Fills the nodes to root for bones and builds hierarchy
  105266. */
  105267. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  105268. // Creates nodes for root
  105269. for (var nde in gltfRuntime.nodes) {
  105270. var node = gltfRuntime.nodes[nde];
  105271. var id = nde;
  105272. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  105273. continue;
  105274. }
  105275. // Create node to root bone
  105276. var mat = configureBoneTransformation(node);
  105277. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  105278. bone.id = id;
  105279. nodesToRoot.push({ bone: bone, node: node, id: id });
  105280. }
  105281. // Parenting
  105282. for (var i = 0; i < nodesToRoot.length; i++) {
  105283. var nodeToRoot = nodesToRoot[i];
  105284. var children = nodeToRoot.node.children;
  105285. for (var j = 0; j < children.length; j++) {
  105286. var child = null;
  105287. for (var k = 0; k < nodesToRoot.length; k++) {
  105288. if (nodesToRoot[k].id === children[j]) {
  105289. child = nodesToRoot[k];
  105290. break;
  105291. }
  105292. }
  105293. if (child) {
  105294. child.bone._parent = nodeToRoot.bone;
  105295. nodeToRoot.bone.children.push(child.bone);
  105296. }
  105297. }
  105298. }
  105299. };
  105300. /**
  105301. * Imports a skeleton
  105302. */
  105303. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  105304. if (!newSkeleton) {
  105305. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  105306. }
  105307. if (!skins.babylonSkeleton) {
  105308. return newSkeleton;
  105309. }
  105310. // Find the root bones
  105311. var nodesToRoot = [];
  105312. var nodesToRootToAdd = [];
  105313. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  105314. newSkeleton.bones = [];
  105315. // Joints
  105316. for (var i = 0; i < skins.jointNames.length; i++) {
  105317. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  105318. if (!jointNode) {
  105319. continue;
  105320. }
  105321. var node = jointNode.node;
  105322. if (!node) {
  105323. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  105324. continue;
  105325. }
  105326. var id = jointNode.id;
  105327. // Optimize, if the bone already exists...
  105328. var existingBone = gltfRuntime.scene.getBoneByID(id);
  105329. if (existingBone) {
  105330. newSkeleton.bones.push(existingBone);
  105331. continue;
  105332. }
  105333. // Search for parent bone
  105334. var foundBone = false;
  105335. var parentBone = null;
  105336. for (var j = 0; j < i; j++) {
  105337. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  105338. if (!jointNode_1) {
  105339. continue;
  105340. }
  105341. var joint = jointNode_1.node;
  105342. if (!joint) {
  105343. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  105344. continue;
  105345. }
  105346. var children = joint.children;
  105347. if (!children) {
  105348. continue;
  105349. }
  105350. foundBone = false;
  105351. for (var k = 0; k < children.length; k++) {
  105352. if (children[k] === id) {
  105353. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  105354. foundBone = true;
  105355. break;
  105356. }
  105357. }
  105358. if (foundBone) {
  105359. break;
  105360. }
  105361. }
  105362. // Create bone
  105363. var mat = configureBoneTransformation(node);
  105364. if (!parentBone && nodesToRoot.length > 0) {
  105365. parentBone = getNodeToRoot(nodesToRoot, id);
  105366. if (parentBone) {
  105367. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  105368. nodesToRootToAdd.push(parentBone);
  105369. }
  105370. }
  105371. }
  105372. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  105373. bone.id = id;
  105374. }
  105375. // Polish
  105376. var bones = newSkeleton.bones;
  105377. newSkeleton.bones = [];
  105378. for (var i = 0; i < skins.jointNames.length; i++) {
  105379. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  105380. if (!jointNode) {
  105381. continue;
  105382. }
  105383. for (var j = 0; j < bones.length; j++) {
  105384. if (bones[j].id === jointNode.id) {
  105385. newSkeleton.bones.push(bones[j]);
  105386. break;
  105387. }
  105388. }
  105389. }
  105390. newSkeleton.prepare();
  105391. // Finish
  105392. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  105393. newSkeleton.bones.push(nodesToRootToAdd[i]);
  105394. }
  105395. return newSkeleton;
  105396. };
  105397. /**
  105398. * Imports a mesh and its geometries
  105399. */
  105400. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  105401. if (!newMesh) {
  105402. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  105403. newMesh.id = id;
  105404. }
  105405. if (!node.babylonNode) {
  105406. return newMesh;
  105407. }
  105408. var subMaterials = [];
  105409. var vertexData = null;
  105410. var verticesStarts = new Array();
  105411. var verticesCounts = new Array();
  105412. var indexStarts = new Array();
  105413. var indexCounts = new Array();
  105414. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  105415. var meshID = meshes[meshIndex];
  105416. var mesh = gltfRuntime.meshes[meshID];
  105417. if (!mesh) {
  105418. continue;
  105419. }
  105420. // Positions, normals and UVs
  105421. for (var i = 0; i < mesh.primitives.length; i++) {
  105422. // Temporary vertex data
  105423. var tempVertexData = new BABYLON.VertexData();
  105424. var primitive = mesh.primitives[i];
  105425. if (primitive.mode !== 4) {
  105426. // continue;
  105427. }
  105428. var attributes = primitive.attributes;
  105429. var accessor = null;
  105430. var buffer = null;
  105431. // Set positions, normal and uvs
  105432. for (var semantic in attributes) {
  105433. // Link accessor and buffer view
  105434. accessor = gltfRuntime.accessors[attributes[semantic]];
  105435. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  105436. if (semantic === "NORMAL") {
  105437. tempVertexData.normals = new Float32Array(buffer.length);
  105438. tempVertexData.normals.set(buffer);
  105439. }
  105440. else if (semantic === "POSITION") {
  105441. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  105442. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  105443. for (var j = 0; j < buffer.length; j += 4) {
  105444. tempVertexData.positions[j] = buffer[j];
  105445. tempVertexData.positions[j + 1] = buffer[j + 1];
  105446. tempVertexData.positions[j + 2] = buffer[j + 2];
  105447. }
  105448. }
  105449. else {
  105450. tempVertexData.positions = new Float32Array(buffer.length);
  105451. tempVertexData.positions.set(buffer);
  105452. }
  105453. verticesCounts.push(tempVertexData.positions.length);
  105454. }
  105455. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  105456. var channel = Number(semantic.split("_")[1]);
  105457. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  105458. var uvs = new Float32Array(buffer.length);
  105459. uvs.set(buffer);
  105460. normalizeUVs(uvs);
  105461. tempVertexData.set(uvs, uvKind);
  105462. }
  105463. else if (semantic === "JOINT") {
  105464. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  105465. tempVertexData.matricesIndices.set(buffer);
  105466. }
  105467. else if (semantic === "WEIGHT") {
  105468. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  105469. tempVertexData.matricesWeights.set(buffer);
  105470. }
  105471. else if (semantic === "COLOR") {
  105472. tempVertexData.colors = new Float32Array(buffer.length);
  105473. tempVertexData.colors.set(buffer);
  105474. }
  105475. }
  105476. // Indices
  105477. accessor = gltfRuntime.accessors[primitive.indices];
  105478. if (accessor) {
  105479. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  105480. tempVertexData.indices = new Int32Array(buffer.length);
  105481. tempVertexData.indices.set(buffer);
  105482. indexCounts.push(tempVertexData.indices.length);
  105483. }
  105484. else {
  105485. // Set indices on the fly
  105486. var indices = [];
  105487. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  105488. indices.push(j);
  105489. }
  105490. tempVertexData.indices = new Int32Array(indices);
  105491. indexCounts.push(tempVertexData.indices.length);
  105492. }
  105493. if (!vertexData) {
  105494. vertexData = tempVertexData;
  105495. }
  105496. else {
  105497. vertexData.merge(tempVertexData);
  105498. }
  105499. // Sub material
  105500. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  105501. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  105502. // Update vertices start and index start
  105503. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  105504. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  105505. }
  105506. }
  105507. var material;
  105508. if (subMaterials.length > 1) {
  105509. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  105510. material.subMaterials = subMaterials;
  105511. }
  105512. else {
  105513. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  105514. }
  105515. if (subMaterials.length === 1) {
  105516. material = subMaterials[0];
  105517. }
  105518. if (!newMesh.material) {
  105519. newMesh.material = material;
  105520. }
  105521. // Apply geometry
  105522. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  105523. newMesh.computeWorldMatrix(true);
  105524. // Apply submeshes
  105525. newMesh.subMeshes = [];
  105526. var index = 0;
  105527. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  105528. var meshID = meshes[meshIndex];
  105529. var mesh = gltfRuntime.meshes[meshID];
  105530. if (!mesh) {
  105531. continue;
  105532. }
  105533. for (var i = 0; i < mesh.primitives.length; i++) {
  105534. if (mesh.primitives[i].mode !== 4) {
  105535. //continue;
  105536. }
  105537. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  105538. index++;
  105539. }
  105540. }
  105541. // Finish
  105542. return newMesh;
  105543. };
  105544. /**
  105545. * Configure node transformation from position, rotation and scaling
  105546. */
  105547. var configureNode = function (newNode, position, rotation, scaling) {
  105548. if (newNode.position) {
  105549. newNode.position = position;
  105550. }
  105551. if (newNode.rotationQuaternion || newNode.rotation) {
  105552. newNode.rotationQuaternion = rotation;
  105553. }
  105554. if (newNode.scaling) {
  105555. newNode.scaling = scaling;
  105556. }
  105557. };
  105558. /**
  105559. * Configures node from transformation matrix
  105560. */
  105561. var configureNodeFromMatrix = function (newNode, node, parent) {
  105562. if (node.matrix) {
  105563. var position = new BABYLON.Vector3(0, 0, 0);
  105564. var rotation = new BABYLON.Quaternion();
  105565. var scaling = new BABYLON.Vector3(0, 0, 0);
  105566. var mat = BABYLON.Matrix.FromArray(node.matrix);
  105567. mat.decompose(scaling, rotation, position);
  105568. configureNode(newNode, position, rotation, scaling);
  105569. }
  105570. else if (node.translation && node.rotation && node.scale) {
  105571. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  105572. }
  105573. newNode.computeWorldMatrix(true);
  105574. };
  105575. /**
  105576. * Imports a node
  105577. */
  105578. var importNode = function (gltfRuntime, node, id, parent) {
  105579. var lastNode = null;
  105580. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  105581. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  105582. return null;
  105583. }
  105584. }
  105585. // Meshes
  105586. if (node.skin) {
  105587. if (node.meshes) {
  105588. var skin = gltfRuntime.skins[node.skin];
  105589. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  105590. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  105591. if (newMesh.skeleton === null) {
  105592. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  105593. if (!skin.babylonSkeleton) {
  105594. skin.babylonSkeleton = newMesh.skeleton;
  105595. }
  105596. }
  105597. lastNode = newMesh;
  105598. }
  105599. }
  105600. else if (node.meshes) {
  105601. /**
  105602. * Improve meshes property
  105603. */
  105604. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  105605. lastNode = newMesh;
  105606. }
  105607. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  105608. var light = gltfRuntime.lights[node.light];
  105609. if (light) {
  105610. if (light.type === "ambient") {
  105611. var ambienLight = light[light.type];
  105612. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  105613. hemiLight.name = node.name || "";
  105614. if (ambienLight.color) {
  105615. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  105616. }
  105617. lastNode = hemiLight;
  105618. }
  105619. else if (light.type === "directional") {
  105620. var directionalLight = light[light.type];
  105621. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  105622. dirLight.name = node.name || "";
  105623. if (directionalLight.color) {
  105624. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  105625. }
  105626. lastNode = dirLight;
  105627. }
  105628. else if (light.type === "point") {
  105629. var pointLight = light[light.type];
  105630. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  105631. ptLight.name = node.name || "";
  105632. if (pointLight.color) {
  105633. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  105634. }
  105635. lastNode = ptLight;
  105636. }
  105637. else if (light.type === "spot") {
  105638. var spotLight = light[light.type];
  105639. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  105640. spLight.name = node.name || "";
  105641. if (spotLight.color) {
  105642. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  105643. }
  105644. if (spotLight.fallOfAngle) {
  105645. spLight.angle = spotLight.fallOfAngle;
  105646. }
  105647. if (spotLight.fallOffExponent) {
  105648. spLight.exponent = spotLight.fallOffExponent;
  105649. }
  105650. lastNode = spLight;
  105651. }
  105652. }
  105653. }
  105654. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  105655. var camera = gltfRuntime.cameras[node.camera];
  105656. if (camera) {
  105657. if (camera.type === "orthographic") {
  105658. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  105659. orthoCamera.name = node.name || "";
  105660. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  105661. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  105662. lastNode = orthoCamera;
  105663. }
  105664. else if (camera.type === "perspective") {
  105665. var perspectiveCamera = camera[camera.type];
  105666. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  105667. persCamera.name = node.name || "";
  105668. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  105669. if (!perspectiveCamera.aspectRatio) {
  105670. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  105671. }
  105672. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  105673. persCamera.maxZ = perspectiveCamera.zfar;
  105674. persCamera.minZ = perspectiveCamera.znear;
  105675. }
  105676. lastNode = persCamera;
  105677. }
  105678. }
  105679. }
  105680. // Empty node
  105681. if (!node.jointName) {
  105682. if (node.babylonNode) {
  105683. return node.babylonNode;
  105684. }
  105685. else if (lastNode === null) {
  105686. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  105687. node.babylonNode = dummy;
  105688. lastNode = dummy;
  105689. }
  105690. }
  105691. if (lastNode !== null) {
  105692. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  105693. configureNodeFromMatrix(lastNode, node, parent);
  105694. }
  105695. else {
  105696. var translation = node.translation || [0, 0, 0];
  105697. var rotation = node.rotation || [0, 0, 0, 1];
  105698. var scale = node.scale || [1, 1, 1];
  105699. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  105700. }
  105701. lastNode.updateCache(true);
  105702. node.babylonNode = lastNode;
  105703. }
  105704. return lastNode;
  105705. };
  105706. /**
  105707. * Traverses nodes and creates them
  105708. */
  105709. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  105710. if (meshIncluded === void 0) { meshIncluded = false; }
  105711. var node = gltfRuntime.nodes[id];
  105712. var newNode = null;
  105713. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  105714. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  105715. meshIncluded = true;
  105716. }
  105717. else {
  105718. meshIncluded = false;
  105719. }
  105720. }
  105721. else {
  105722. meshIncluded = true;
  105723. }
  105724. if (!node.jointName && meshIncluded) {
  105725. newNode = importNode(gltfRuntime, node, id, parent);
  105726. if (newNode !== null) {
  105727. newNode.id = id;
  105728. newNode.parent = parent;
  105729. }
  105730. }
  105731. if (node.children) {
  105732. for (var i = 0; i < node.children.length; i++) {
  105733. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  105734. }
  105735. }
  105736. };
  105737. /**
  105738. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  105739. */
  105740. var postLoad = function (gltfRuntime) {
  105741. // Nodes
  105742. var currentScene = gltfRuntime.currentScene;
  105743. if (currentScene) {
  105744. for (var i = 0; i < currentScene.nodes.length; i++) {
  105745. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  105746. }
  105747. }
  105748. else {
  105749. for (var thing in gltfRuntime.scenes) {
  105750. currentScene = gltfRuntime.scenes[thing];
  105751. for (var i = 0; i < currentScene.nodes.length; i++) {
  105752. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  105753. }
  105754. }
  105755. }
  105756. // Set animations
  105757. loadAnimations(gltfRuntime);
  105758. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  105759. var skeleton = gltfRuntime.scene.skeletons[i];
  105760. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  105761. }
  105762. };
  105763. /**
  105764. * onBind shaderrs callback to set uniforms and matrices
  105765. */
  105766. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  105767. var materialValues = material.values || technique.parameters;
  105768. for (var unif in unTreatedUniforms) {
  105769. var uniform = unTreatedUniforms[unif];
  105770. var type = uniform.type;
  105771. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  105772. if (uniform.semantic && !uniform.source && !uniform.node) {
  105773. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  105774. }
  105775. else if (uniform.semantic && (uniform.source || uniform.node)) {
  105776. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  105777. if (source === null) {
  105778. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  105779. }
  105780. if (source === null) {
  105781. continue;
  105782. }
  105783. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  105784. }
  105785. }
  105786. else {
  105787. var value = materialValues[technique.uniforms[unif]];
  105788. if (!value) {
  105789. continue;
  105790. }
  105791. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  105792. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  105793. if (texture === null || texture === undefined) {
  105794. continue;
  105795. }
  105796. shaderMaterial.getEffect().setTexture(unif, texture);
  105797. }
  105798. else {
  105799. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  105800. }
  105801. }
  105802. }
  105803. onSuccess(shaderMaterial);
  105804. };
  105805. /**
  105806. * Prepare uniforms to send the only one time
  105807. * Loads the appropriate textures
  105808. */
  105809. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  105810. var materialValues = material.values || technique.parameters;
  105811. var techniqueUniforms = technique.uniforms;
  105812. /**
  105813. * Prepare values here (not matrices)
  105814. */
  105815. for (var unif in unTreatedUniforms) {
  105816. var uniform = unTreatedUniforms[unif];
  105817. var type = uniform.type;
  105818. var value = materialValues[techniqueUniforms[unif]];
  105819. if (value === undefined) {
  105820. // In case the value is the same for all materials
  105821. value = uniform.value;
  105822. }
  105823. if (!value) {
  105824. continue;
  105825. }
  105826. var onLoadTexture = function (uniformName) {
  105827. return function (texture) {
  105828. if (uniform.value && uniformName) {
  105829. // Static uniform
  105830. shaderMaterial.setTexture(uniformName, texture);
  105831. delete unTreatedUniforms[uniformName];
  105832. }
  105833. };
  105834. };
  105835. // Texture (sampler2D)
  105836. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  105837. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  105838. }
  105839. else {
  105840. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  105841. // Static uniform
  105842. delete unTreatedUniforms[unif];
  105843. }
  105844. }
  105845. }
  105846. };
  105847. /**
  105848. * Shader compilation failed
  105849. */
  105850. var onShaderCompileError = function (program, shaderMaterial, onError) {
  105851. return function (effect, error) {
  105852. shaderMaterial.dispose(true);
  105853. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  105854. };
  105855. };
  105856. /**
  105857. * Shader compilation success
  105858. */
  105859. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  105860. return function (_) {
  105861. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  105862. shaderMaterial.onBind = function (mesh) {
  105863. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  105864. };
  105865. };
  105866. };
  105867. /**
  105868. * Returns the appropriate uniform if already handled by babylon
  105869. */
  105870. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  105871. for (var unif in technique.uniforms) {
  105872. var uniform = technique.uniforms[unif];
  105873. var uniformParameter = technique.parameters[uniform];
  105874. if (tokenizer.currentIdentifier === unif) {
  105875. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  105876. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  105877. if (transformIndex !== -1) {
  105878. delete unTreatedUniforms[unif];
  105879. return babylonTransforms[transformIndex];
  105880. }
  105881. }
  105882. }
  105883. }
  105884. return tokenizer.currentIdentifier;
  105885. };
  105886. /**
  105887. * All shaders loaded. Create materials one by one
  105888. */
  105889. var importMaterials = function (gltfRuntime) {
  105890. // Create materials
  105891. for (var mat in gltfRuntime.materials) {
  105892. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  105893. }
  105894. };
  105895. /**
  105896. * Implementation of the base glTF spec
  105897. */
  105898. var GLTFLoaderBase = /** @class */ (function () {
  105899. function GLTFLoaderBase() {
  105900. }
  105901. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  105902. var gltfRuntime = {
  105903. extensions: {},
  105904. accessors: {},
  105905. buffers: {},
  105906. bufferViews: {},
  105907. meshes: {},
  105908. lights: {},
  105909. cameras: {},
  105910. nodes: {},
  105911. images: {},
  105912. textures: {},
  105913. shaders: {},
  105914. programs: {},
  105915. samplers: {},
  105916. techniques: {},
  105917. materials: {},
  105918. animations: {},
  105919. skins: {},
  105920. extensionsUsed: [],
  105921. scenes: {},
  105922. buffersCount: 0,
  105923. shaderscount: 0,
  105924. scene: scene,
  105925. rootUrl: rootUrl,
  105926. loadedBufferCount: 0,
  105927. loadedBufferViews: {},
  105928. loadedShaderCount: 0,
  105929. importOnlyMeshes: false,
  105930. dummyNodes: []
  105931. };
  105932. // Parse
  105933. if (parsedData.extensions) {
  105934. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  105935. }
  105936. if (parsedData.extensionsUsed) {
  105937. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  105938. }
  105939. if (parsedData.buffers) {
  105940. parseBuffers(parsedData.buffers, gltfRuntime);
  105941. }
  105942. if (parsedData.bufferViews) {
  105943. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  105944. }
  105945. if (parsedData.accessors) {
  105946. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  105947. }
  105948. if (parsedData.meshes) {
  105949. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  105950. }
  105951. if (parsedData.lights) {
  105952. parseObject(parsedData.lights, "lights", gltfRuntime);
  105953. }
  105954. if (parsedData.cameras) {
  105955. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  105956. }
  105957. if (parsedData.nodes) {
  105958. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  105959. }
  105960. if (parsedData.images) {
  105961. parseObject(parsedData.images, "images", gltfRuntime);
  105962. }
  105963. if (parsedData.textures) {
  105964. parseObject(parsedData.textures, "textures", gltfRuntime);
  105965. }
  105966. if (parsedData.shaders) {
  105967. parseShaders(parsedData.shaders, gltfRuntime);
  105968. }
  105969. if (parsedData.programs) {
  105970. parseObject(parsedData.programs, "programs", gltfRuntime);
  105971. }
  105972. if (parsedData.samplers) {
  105973. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  105974. }
  105975. if (parsedData.techniques) {
  105976. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  105977. }
  105978. if (parsedData.materials) {
  105979. parseObject(parsedData.materials, "materials", gltfRuntime);
  105980. }
  105981. if (parsedData.animations) {
  105982. parseObject(parsedData.animations, "animations", gltfRuntime);
  105983. }
  105984. if (parsedData.skins) {
  105985. parseObject(parsedData.skins, "skins", gltfRuntime);
  105986. }
  105987. if (parsedData.scenes) {
  105988. gltfRuntime.scenes = parsedData.scenes;
  105989. }
  105990. if (parsedData.scene && parsedData.scenes) {
  105991. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  105992. }
  105993. return gltfRuntime;
  105994. };
  105995. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  105996. var buffer = gltfRuntime.buffers[id];
  105997. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  105998. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  105999. }
  106000. else {
  106001. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  106002. if (request) {
  106003. onError(request.status + " " + request.statusText);
  106004. }
  106005. });
  106006. }
  106007. };
  106008. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  106009. var texture = gltfRuntime.textures[id];
  106010. if (!texture || !texture.source) {
  106011. onError("");
  106012. return;
  106013. }
  106014. if (texture.babylonTexture) {
  106015. onSuccess(null);
  106016. return;
  106017. }
  106018. var source = gltfRuntime.images[texture.source];
  106019. if (BABYLON.Tools.IsBase64(source.uri)) {
  106020. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  106021. }
  106022. else {
  106023. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  106024. if (request) {
  106025. onError(request.status + " " + request.statusText);
  106026. }
  106027. });
  106028. }
  106029. };
  106030. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  106031. var texture = gltfRuntime.textures[id];
  106032. if (texture.babylonTexture) {
  106033. onSuccess(texture.babylonTexture);
  106034. return;
  106035. }
  106036. var sampler = gltfRuntime.samplers[texture.sampler];
  106037. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  106038. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  106039. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  106040. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  106041. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  106042. var blob = new Blob([buffer]);
  106043. var blobURL = URL.createObjectURL(blob);
  106044. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  106045. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  106046. if (sampler.wrapS !== undefined) {
  106047. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  106048. }
  106049. if (sampler.wrapT !== undefined) {
  106050. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  106051. }
  106052. newTexture.name = id;
  106053. texture.babylonTexture = newTexture;
  106054. onSuccess(newTexture);
  106055. };
  106056. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  106057. var shader = gltfRuntime.shaders[id];
  106058. if (BABYLON.Tools.IsBase64(shader.uri)) {
  106059. var shaderString = atob(shader.uri.split(",")[1]);
  106060. onSuccess(shaderString);
  106061. }
  106062. else {
  106063. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  106064. if (request) {
  106065. onError(request.status + " " + request.statusText);
  106066. }
  106067. });
  106068. }
  106069. };
  106070. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  106071. var material = gltfRuntime.materials[id];
  106072. if (!material.technique) {
  106073. if (onError) {
  106074. onError("No technique found.");
  106075. }
  106076. return;
  106077. }
  106078. var technique = gltfRuntime.techniques[material.technique];
  106079. if (!technique) {
  106080. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  106081. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  106082. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  106083. onSuccess(defaultMaterial);
  106084. return;
  106085. }
  106086. var program = gltfRuntime.programs[technique.program];
  106087. var states = technique.states;
  106088. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  106089. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  106090. var newVertexShader = "";
  106091. var newPixelShader = "";
  106092. var vertexTokenizer = new Tokenizer(vertexShader);
  106093. var pixelTokenizer = new Tokenizer(pixelShader);
  106094. var unTreatedUniforms = {};
  106095. var uniforms = [];
  106096. var attributes = [];
  106097. var samplers = [];
  106098. // Fill uniform, sampler2D and attributes
  106099. for (var unif in technique.uniforms) {
  106100. var uniform = technique.uniforms[unif];
  106101. var uniformParameter = technique.parameters[uniform];
  106102. unTreatedUniforms[unif] = uniformParameter;
  106103. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  106104. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  106105. if (transformIndex !== -1) {
  106106. uniforms.push(babylonTransforms[transformIndex]);
  106107. delete unTreatedUniforms[unif];
  106108. }
  106109. else {
  106110. uniforms.push(unif);
  106111. }
  106112. }
  106113. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  106114. samplers.push(unif);
  106115. }
  106116. else {
  106117. uniforms.push(unif);
  106118. }
  106119. }
  106120. for (var attr in technique.attributes) {
  106121. var attribute = technique.attributes[attr];
  106122. var attributeParameter = technique.parameters[attribute];
  106123. if (attributeParameter.semantic) {
  106124. attributes.push(getAttribute(attributeParameter));
  106125. }
  106126. }
  106127. // Configure vertex shader
  106128. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  106129. var tokenType = vertexTokenizer.currentToken;
  106130. if (tokenType !== ETokenType.IDENTIFIER) {
  106131. newVertexShader += vertexTokenizer.currentString;
  106132. continue;
  106133. }
  106134. var foundAttribute = false;
  106135. for (var attr in technique.attributes) {
  106136. var attribute = technique.attributes[attr];
  106137. var attributeParameter = technique.parameters[attribute];
  106138. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  106139. newVertexShader += getAttribute(attributeParameter);
  106140. foundAttribute = true;
  106141. break;
  106142. }
  106143. }
  106144. if (foundAttribute) {
  106145. continue;
  106146. }
  106147. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  106148. }
  106149. // Configure pixel shader
  106150. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  106151. var tokenType = pixelTokenizer.currentToken;
  106152. if (tokenType !== ETokenType.IDENTIFIER) {
  106153. newPixelShader += pixelTokenizer.currentString;
  106154. continue;
  106155. }
  106156. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  106157. }
  106158. // Create shader material
  106159. var shaderPath = {
  106160. vertex: program.vertexShader + id,
  106161. fragment: program.fragmentShader + id
  106162. };
  106163. var options = {
  106164. attributes: attributes,
  106165. uniforms: uniforms,
  106166. samplers: samplers,
  106167. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  106168. };
  106169. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  106170. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  106171. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  106172. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  106173. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  106174. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  106175. if (states && states.functions) {
  106176. var functions = states.functions;
  106177. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  106178. shaderMaterial.backFaceCulling = false;
  106179. }
  106180. var blendFunc = functions.blendFuncSeparate;
  106181. if (blendFunc) {
  106182. 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) {
  106183. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  106184. }
  106185. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  106186. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  106187. }
  106188. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  106189. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  106190. }
  106191. 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) {
  106192. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  106193. }
  106194. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  106195. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  106196. }
  106197. 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) {
  106198. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  106199. }
  106200. }
  106201. }
  106202. };
  106203. return GLTFLoaderBase;
  106204. }());
  106205. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  106206. /**
  106207. * glTF V1 Loader
  106208. */
  106209. var GLTFLoader = /** @class */ (function () {
  106210. function GLTFLoader() {
  106211. // #region Stubs for IGLTFLoader interface
  106212. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  106213. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  106214. this.compileMaterials = false;
  106215. this.useClipPlane = false;
  106216. this.compileShadowGenerators = false;
  106217. this.onDisposeObservable = new BABYLON.Observable();
  106218. this.onMeshLoadedObservable = new BABYLON.Observable();
  106219. this.onTextureLoadedObservable = new BABYLON.Observable();
  106220. this.onMaterialLoadedObservable = new BABYLON.Observable();
  106221. this.onCompleteObservable = new BABYLON.Observable();
  106222. this.onExtensionLoadedObservable = new BABYLON.Observable();
  106223. this.state = null;
  106224. }
  106225. GLTFLoader.RegisterExtension = function (extension) {
  106226. if (GLTFLoader.Extensions[extension.name]) {
  106227. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  106228. return;
  106229. }
  106230. GLTFLoader.Extensions[extension.name] = extension;
  106231. };
  106232. GLTFLoader.prototype.dispose = function () { };
  106233. // #endregion
  106234. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  106235. var _this = this;
  106236. scene.useRightHandedSystem = true;
  106237. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  106238. gltfRuntime.importOnlyMeshes = true;
  106239. if (meshesNames === "") {
  106240. gltfRuntime.importMeshesNames = [];
  106241. }
  106242. else if (typeof meshesNames === "string") {
  106243. gltfRuntime.importMeshesNames = [meshesNames];
  106244. }
  106245. else if (meshesNames && !(meshesNames instanceof Array)) {
  106246. gltfRuntime.importMeshesNames = [meshesNames];
  106247. }
  106248. else {
  106249. gltfRuntime.importMeshesNames = [];
  106250. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  106251. }
  106252. // Create nodes
  106253. _this._createNodes(gltfRuntime);
  106254. var meshes = new Array();
  106255. var skeletons = new Array();
  106256. // Fill arrays of meshes and skeletons
  106257. for (var nde in gltfRuntime.nodes) {
  106258. var node = gltfRuntime.nodes[nde];
  106259. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  106260. meshes.push(node.babylonNode);
  106261. }
  106262. }
  106263. for (var skl in gltfRuntime.skins) {
  106264. var skin = gltfRuntime.skins[skl];
  106265. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  106266. skeletons.push(skin.babylonSkeleton);
  106267. }
  106268. }
  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 && onSuccess) {
  106275. onSuccess(meshes, [], skeletons);
  106276. }
  106277. });
  106278. }, onProgress);
  106279. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  106280. onSuccess(meshes, [], skeletons);
  106281. }
  106282. }, onError);
  106283. return true;
  106284. };
  106285. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  106286. var _this = this;
  106287. return new Promise(function (resolve, reject) {
  106288. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  106289. resolve({
  106290. meshes: meshes,
  106291. particleSystems: particleSystems,
  106292. skeletons: skeletons
  106293. });
  106294. }, onProgress, function (message) {
  106295. reject(new Error(message));
  106296. });
  106297. });
  106298. };
  106299. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  106300. var _this = this;
  106301. scene.useRightHandedSystem = true;
  106302. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  106303. // Load runtime extensios
  106304. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  106305. // Create nodes
  106306. _this._createNodes(gltfRuntime);
  106307. // Load buffers, shaders, materials, etc.
  106308. _this._loadBuffersAsync(gltfRuntime, function () {
  106309. _this._loadShadersAsync(gltfRuntime, function () {
  106310. importMaterials(gltfRuntime);
  106311. postLoad(gltfRuntime);
  106312. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  106313. onSuccess();
  106314. }
  106315. });
  106316. });
  106317. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  106318. onSuccess();
  106319. }
  106320. }, onError);
  106321. }, onError);
  106322. };
  106323. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  106324. var _this = this;
  106325. return new Promise(function (resolve, reject) {
  106326. _this._loadAsync(scene, data, rootUrl, function () {
  106327. resolve();
  106328. }, onProgress, function (message) {
  106329. reject(new Error(message));
  106330. });
  106331. });
  106332. };
  106333. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  106334. var hasShaders = false;
  106335. var processShader = function (sha, shader) {
  106336. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  106337. gltfRuntime.loadedShaderCount++;
  106338. if (shaderString) {
  106339. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  106340. }
  106341. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  106342. onload();
  106343. }
  106344. }, function () {
  106345. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  106346. });
  106347. };
  106348. for (var sha in gltfRuntime.shaders) {
  106349. hasShaders = true;
  106350. var shader = gltfRuntime.shaders[sha];
  106351. if (shader) {
  106352. processShader.bind(this, sha, shader)();
  106353. }
  106354. else {
  106355. BABYLON.Tools.Error("No shader named: " + sha);
  106356. }
  106357. }
  106358. if (!hasShaders) {
  106359. onload();
  106360. }
  106361. };
  106362. ;
  106363. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  106364. var hasBuffers = false;
  106365. var processBuffer = function (buf, buffer) {
  106366. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  106367. gltfRuntime.loadedBufferCount++;
  106368. if (bufferView) {
  106369. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  106370. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  106371. }
  106372. gltfRuntime.loadedBufferViews[buf] = bufferView;
  106373. }
  106374. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  106375. onLoad();
  106376. }
  106377. }, function () {
  106378. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  106379. });
  106380. };
  106381. for (var buf in gltfRuntime.buffers) {
  106382. hasBuffers = true;
  106383. var buffer = gltfRuntime.buffers[buf];
  106384. if (buffer) {
  106385. processBuffer.bind(this, buf, buffer)();
  106386. }
  106387. else {
  106388. BABYLON.Tools.Error("No buffer named: " + buf);
  106389. }
  106390. }
  106391. if (!hasBuffers) {
  106392. onLoad();
  106393. }
  106394. };
  106395. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  106396. var currentScene = gltfRuntime.currentScene;
  106397. if (currentScene) {
  106398. // Only one scene even if multiple scenes are defined
  106399. for (var i = 0; i < currentScene.nodes.length; i++) {
  106400. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  106401. }
  106402. }
  106403. else {
  106404. // Load all scenes
  106405. for (var thing in gltfRuntime.scenes) {
  106406. currentScene = gltfRuntime.scenes[thing];
  106407. for (var i = 0; i < currentScene.nodes.length; i++) {
  106408. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  106409. }
  106410. }
  106411. }
  106412. };
  106413. GLTFLoader.Extensions = {};
  106414. return GLTFLoader;
  106415. }());
  106416. GLTF1.GLTFLoader = GLTFLoader;
  106417. ;
  106418. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  106419. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  106420. })(BABYLON || (BABYLON = {}));
  106421. //# sourceMappingURL=babylon.glTFLoader.js.map
  106422. var BABYLON;
  106423. (function (BABYLON) {
  106424. var GLTF1;
  106425. (function (GLTF1) {
  106426. /**
  106427. * Utils functions for GLTF
  106428. */
  106429. var GLTFUtils = /** @class */ (function () {
  106430. function GLTFUtils() {
  106431. }
  106432. /**
  106433. * Sets the given "parameter" matrix
  106434. * @param scene: the {BABYLON.Scene} object
  106435. * @param source: the source node where to pick the matrix
  106436. * @param parameter: the GLTF technique parameter
  106437. * @param uniformName: the name of the shader's uniform
  106438. * @param shaderMaterial: the shader material
  106439. */
  106440. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  106441. var mat = null;
  106442. if (parameter.semantic === "MODEL") {
  106443. mat = source.getWorldMatrix();
  106444. }
  106445. else if (parameter.semantic === "PROJECTION") {
  106446. mat = scene.getProjectionMatrix();
  106447. }
  106448. else if (parameter.semantic === "VIEW") {
  106449. mat = scene.getViewMatrix();
  106450. }
  106451. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  106452. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  106453. }
  106454. else if (parameter.semantic === "MODELVIEW") {
  106455. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  106456. }
  106457. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  106458. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  106459. }
  106460. else if (parameter.semantic === "MODELINVERSE") {
  106461. mat = source.getWorldMatrix().invert();
  106462. }
  106463. else if (parameter.semantic === "VIEWINVERSE") {
  106464. mat = scene.getViewMatrix().invert();
  106465. }
  106466. else if (parameter.semantic === "PROJECTIONINVERSE") {
  106467. mat = scene.getProjectionMatrix().invert();
  106468. }
  106469. else if (parameter.semantic === "MODELVIEWINVERSE") {
  106470. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  106471. }
  106472. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  106473. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  106474. }
  106475. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  106476. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  106477. }
  106478. else {
  106479. debugger;
  106480. }
  106481. if (mat) {
  106482. switch (parameter.type) {
  106483. case GLTF1.EParameterType.FLOAT_MAT2:
  106484. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  106485. break;
  106486. case GLTF1.EParameterType.FLOAT_MAT3:
  106487. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  106488. break;
  106489. case GLTF1.EParameterType.FLOAT_MAT4:
  106490. shaderMaterial.setMatrix(uniformName, mat);
  106491. break;
  106492. default: break;
  106493. }
  106494. }
  106495. };
  106496. /**
  106497. * Sets the given "parameter" matrix
  106498. * @param shaderMaterial: the shader material
  106499. * @param uniform: the name of the shader's uniform
  106500. * @param value: the value of the uniform
  106501. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  106502. */
  106503. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  106504. switch (type) {
  106505. case GLTF1.EParameterType.FLOAT:
  106506. shaderMaterial.setFloat(uniform, value);
  106507. return true;
  106508. case GLTF1.EParameterType.FLOAT_VEC2:
  106509. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  106510. return true;
  106511. case GLTF1.EParameterType.FLOAT_VEC3:
  106512. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  106513. return true;
  106514. case GLTF1.EParameterType.FLOAT_VEC4:
  106515. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  106516. return true;
  106517. default: return false;
  106518. }
  106519. };
  106520. /**
  106521. * Returns the wrap mode of the texture
  106522. * @param mode: the mode value
  106523. */
  106524. GLTFUtils.GetWrapMode = function (mode) {
  106525. switch (mode) {
  106526. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  106527. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  106528. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  106529. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  106530. }
  106531. };
  106532. /**
  106533. * Returns the byte stride giving an accessor
  106534. * @param accessor: the GLTF accessor objet
  106535. */
  106536. GLTFUtils.GetByteStrideFromType = function (accessor) {
  106537. // Needs this function since "byteStride" isn't requiered in glTF format
  106538. var type = accessor.type;
  106539. switch (type) {
  106540. case "VEC2": return 2;
  106541. case "VEC3": return 3;
  106542. case "VEC4": return 4;
  106543. case "MAT2": return 4;
  106544. case "MAT3": return 9;
  106545. case "MAT4": return 16;
  106546. default: return 1;
  106547. }
  106548. };
  106549. /**
  106550. * Returns the texture filter mode giving a mode value
  106551. * @param mode: the filter mode value
  106552. */
  106553. GLTFUtils.GetTextureFilterMode = function (mode) {
  106554. switch (mode) {
  106555. case GLTF1.ETextureFilterType.LINEAR:
  106556. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  106557. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  106558. case GLTF1.ETextureFilterType.NEAREST:
  106559. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  106560. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  106561. }
  106562. };
  106563. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  106564. var byteOffset = bufferView.byteOffset + byteOffset;
  106565. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  106566. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  106567. throw new Error("Buffer access is out of range");
  106568. }
  106569. var buffer = loadedBufferView.buffer;
  106570. byteOffset += loadedBufferView.byteOffset;
  106571. switch (componentType) {
  106572. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  106573. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  106574. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  106575. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  106576. default: return new Float32Array(buffer, byteOffset, byteLength);
  106577. }
  106578. };
  106579. /**
  106580. * Returns a buffer from its accessor
  106581. * @param gltfRuntime: the GLTF runtime
  106582. * @param accessor: the GLTF accessor
  106583. */
  106584. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  106585. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  106586. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  106587. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  106588. };
  106589. /**
  106590. * Decodes a buffer view into a string
  106591. * @param view: the buffer view
  106592. */
  106593. GLTFUtils.DecodeBufferToText = function (view) {
  106594. var result = "";
  106595. var length = view.byteLength;
  106596. for (var i = 0; i < length; ++i) {
  106597. result += String.fromCharCode(view[i]);
  106598. }
  106599. return result;
  106600. };
  106601. /**
  106602. * Returns the default material of gltf. Related to
  106603. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  106604. * @param scene: the Babylon.js scene
  106605. */
  106606. GLTFUtils.GetDefaultMaterial = function (scene) {
  106607. if (!GLTFUtils._DefaultMaterial) {
  106608. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  106609. "precision highp float;",
  106610. "",
  106611. "uniform mat4 worldView;",
  106612. "uniform mat4 projection;",
  106613. "",
  106614. "attribute vec3 position;",
  106615. "",
  106616. "void main(void)",
  106617. "{",
  106618. " gl_Position = projection * worldView * vec4(position, 1.0);",
  106619. "}"
  106620. ].join("\n");
  106621. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  106622. "precision highp float;",
  106623. "",
  106624. "uniform vec4 u_emission;",
  106625. "",
  106626. "void main(void)",
  106627. "{",
  106628. " gl_FragColor = u_emission;",
  106629. "}"
  106630. ].join("\n");
  106631. var shaderPath = {
  106632. vertex: "GLTFDefaultMaterial",
  106633. fragment: "GLTFDefaultMaterial"
  106634. };
  106635. var options = {
  106636. attributes: ["position"],
  106637. uniforms: ["worldView", "projection", "u_emission"],
  106638. samplers: new Array(),
  106639. needAlphaBlending: false
  106640. };
  106641. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  106642. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  106643. }
  106644. return GLTFUtils._DefaultMaterial;
  106645. };
  106646. // The GLTF default material
  106647. GLTFUtils._DefaultMaterial = null;
  106648. return GLTFUtils;
  106649. }());
  106650. GLTF1.GLTFUtils = GLTFUtils;
  106651. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  106652. })(BABYLON || (BABYLON = {}));
  106653. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  106654. var BABYLON;
  106655. (function (BABYLON) {
  106656. var GLTF1;
  106657. (function (GLTF1) {
  106658. var GLTFLoaderExtension = /** @class */ (function () {
  106659. function GLTFLoaderExtension(name) {
  106660. this._name = name;
  106661. }
  106662. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  106663. get: function () {
  106664. return this._name;
  106665. },
  106666. enumerable: true,
  106667. configurable: true
  106668. });
  106669. /**
  106670. * Defines an override for loading the runtime
  106671. * Return true to stop further extensions from loading the runtime
  106672. */
  106673. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  106674. return false;
  106675. };
  106676. /**
  106677. * Defines an onverride for creating gltf runtime
  106678. * Return true to stop further extensions from creating the runtime
  106679. */
  106680. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  106681. return false;
  106682. };
  106683. /**
  106684. * Defines an override for loading buffers
  106685. * Return true to stop further extensions from loading this buffer
  106686. */
  106687. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  106688. return false;
  106689. };
  106690. /**
  106691. * Defines an override for loading texture buffers
  106692. * Return true to stop further extensions from loading this texture data
  106693. */
  106694. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  106695. return false;
  106696. };
  106697. /**
  106698. * Defines an override for creating textures
  106699. * Return true to stop further extensions from loading this texture
  106700. */
  106701. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  106702. return false;
  106703. };
  106704. /**
  106705. * Defines an override for loading shader strings
  106706. * Return true to stop further extensions from loading this shader data
  106707. */
  106708. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  106709. return false;
  106710. };
  106711. /**
  106712. * Defines an override for loading materials
  106713. * Return true to stop further extensions from loading this material
  106714. */
  106715. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  106716. return false;
  106717. };
  106718. // ---------
  106719. // Utilities
  106720. // ---------
  106721. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  106722. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  106723. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  106724. }, function () {
  106725. setTimeout(function () {
  106726. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  106727. });
  106728. });
  106729. };
  106730. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  106731. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  106732. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  106733. }, function () {
  106734. setTimeout(function () {
  106735. onSuccess();
  106736. });
  106737. });
  106738. };
  106739. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  106740. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  106741. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  106742. }, function () {
  106743. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  106744. });
  106745. };
  106746. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  106747. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  106748. };
  106749. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  106750. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  106751. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  106752. }, function () {
  106753. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  106754. });
  106755. };
  106756. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  106757. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  106758. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  106759. }, function () {
  106760. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  106761. });
  106762. };
  106763. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  106764. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  106765. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  106766. }, function () {
  106767. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  106768. });
  106769. };
  106770. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  106771. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  106772. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  106773. }, function () {
  106774. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  106775. });
  106776. };
  106777. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  106778. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  106779. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  106780. if (func(loaderExtension)) {
  106781. return;
  106782. }
  106783. }
  106784. defaultFunc();
  106785. };
  106786. return GLTFLoaderExtension;
  106787. }());
  106788. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  106789. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  106790. })(BABYLON || (BABYLON = {}));
  106791. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  106792. var BABYLON;
  106793. (function (BABYLON) {
  106794. var GLTF1;
  106795. (function (GLTF1) {
  106796. var BinaryExtensionBufferName = "binary_glTF";
  106797. ;
  106798. ;
  106799. var GLTFBinaryExtension = /** @class */ (function (_super) {
  106800. __extends(GLTFBinaryExtension, _super);
  106801. function GLTFBinaryExtension() {
  106802. return _super.call(this, "KHR_binary_glTF") || this;
  106803. }
  106804. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  106805. var extensionsUsed = data.json.extensionsUsed;
  106806. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  106807. return false;
  106808. }
  106809. this._bin = data.bin;
  106810. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  106811. return true;
  106812. };
  106813. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  106814. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  106815. return false;
  106816. }
  106817. if (id !== BinaryExtensionBufferName) {
  106818. return false;
  106819. }
  106820. onSuccess(this._bin);
  106821. return true;
  106822. };
  106823. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  106824. var texture = gltfRuntime.textures[id];
  106825. var source = gltfRuntime.images[texture.source];
  106826. if (!source.extensions || !(this.name in source.extensions)) {
  106827. return false;
  106828. }
  106829. var sourceExt = source.extensions[this.name];
  106830. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  106831. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  106832. onSuccess(buffer);
  106833. return true;
  106834. };
  106835. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  106836. var shader = gltfRuntime.shaders[id];
  106837. if (!shader.extensions || !(this.name in shader.extensions)) {
  106838. return false;
  106839. }
  106840. var binaryExtensionShader = shader.extensions[this.name];
  106841. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  106842. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  106843. setTimeout(function () {
  106844. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  106845. onSuccess(shaderString);
  106846. });
  106847. return true;
  106848. };
  106849. return GLTFBinaryExtension;
  106850. }(GLTF1.GLTFLoaderExtension));
  106851. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  106852. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  106853. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  106854. })(BABYLON || (BABYLON = {}));
  106855. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  106856. var BABYLON;
  106857. (function (BABYLON) {
  106858. var GLTF1;
  106859. (function (GLTF1) {
  106860. ;
  106861. ;
  106862. ;
  106863. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  106864. __extends(GLTFMaterialsCommonExtension, _super);
  106865. function GLTFMaterialsCommonExtension() {
  106866. return _super.call(this, "KHR_materials_common") || this;
  106867. }
  106868. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  106869. if (!gltfRuntime.extensions)
  106870. return false;
  106871. var extension = gltfRuntime.extensions[this.name];
  106872. if (!extension)
  106873. return false;
  106874. // Create lights
  106875. var lights = extension.lights;
  106876. if (lights) {
  106877. for (var thing in lights) {
  106878. var light = lights[thing];
  106879. switch (light.type) {
  106880. case "ambient":
  106881. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  106882. var ambient = light.ambient;
  106883. if (ambient) {
  106884. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  106885. }
  106886. break;
  106887. case "point":
  106888. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  106889. var point = light.point;
  106890. if (point) {
  106891. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  106892. }
  106893. break;
  106894. case "directional":
  106895. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  106896. var directional = light.directional;
  106897. if (directional) {
  106898. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  106899. }
  106900. break;
  106901. case "spot":
  106902. var spot = light.spot;
  106903. if (spot) {
  106904. 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);
  106905. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  106906. }
  106907. break;
  106908. default:
  106909. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  106910. break;
  106911. }
  106912. }
  106913. }
  106914. return false;
  106915. };
  106916. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  106917. var material = gltfRuntime.materials[id];
  106918. if (!material || !material.extensions)
  106919. return false;
  106920. var extension = material.extensions[this.name];
  106921. if (!extension)
  106922. return false;
  106923. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  106924. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  106925. if (extension.technique === "CONSTANT") {
  106926. standardMaterial.disableLighting = true;
  106927. }
  106928. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  106929. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  106930. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  106931. // Ambient
  106932. if (typeof extension.values.ambient === "string") {
  106933. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  106934. }
  106935. else {
  106936. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  106937. }
  106938. // Diffuse
  106939. if (typeof extension.values.diffuse === "string") {
  106940. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  106941. }
  106942. else {
  106943. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  106944. }
  106945. // Emission
  106946. if (typeof extension.values.emission === "string") {
  106947. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  106948. }
  106949. else {
  106950. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  106951. }
  106952. // Specular
  106953. if (typeof extension.values.specular === "string") {
  106954. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  106955. }
  106956. else {
  106957. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  106958. }
  106959. return true;
  106960. };
  106961. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  106962. // Create buffer from texture url
  106963. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  106964. // Create texture from buffer
  106965. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  106966. }, onError);
  106967. };
  106968. return GLTFMaterialsCommonExtension;
  106969. }(GLTF1.GLTFLoaderExtension));
  106970. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  106971. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  106972. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  106973. })(BABYLON || (BABYLON = {}));
  106974. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  106975. var BABYLON;
  106976. (function (BABYLON) {
  106977. var GLTF2;
  106978. (function (GLTF2) {
  106979. var ArrayItem = /** @class */ (function () {
  106980. function ArrayItem() {
  106981. }
  106982. ArrayItem.Assign = function (values) {
  106983. if (values) {
  106984. for (var index = 0; index < values.length; index++) {
  106985. values[index]._index = index;
  106986. }
  106987. }
  106988. };
  106989. return ArrayItem;
  106990. }());
  106991. GLTF2.ArrayItem = ArrayItem;
  106992. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  106993. })(BABYLON || (BABYLON = {}));
  106994. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  106995. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  106996. var BABYLON;
  106997. (function (BABYLON) {
  106998. var GLTF2;
  106999. (function (GLTF2) {
  107000. var GLTFLoader = /** @class */ (function () {
  107001. function GLTFLoader() {
  107002. this._completePromises = new Array();
  107003. this._disposed = false;
  107004. this._state = null;
  107005. this._extensions = {};
  107006. this._defaultSampler = {};
  107007. this._requests = new Array();
  107008. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  107009. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  107010. this.compileMaterials = false;
  107011. this.useClipPlane = false;
  107012. this.compileShadowGenerators = false;
  107013. this.onDisposeObservable = new BABYLON.Observable();
  107014. this.onMeshLoadedObservable = new BABYLON.Observable();
  107015. this.onTextureLoadedObservable = new BABYLON.Observable();
  107016. this.onMaterialLoadedObservable = new BABYLON.Observable();
  107017. this.onExtensionLoadedObservable = new BABYLON.Observable();
  107018. this.onCompleteObservable = new BABYLON.Observable();
  107019. }
  107020. GLTFLoader._Register = function (name, factory) {
  107021. if (GLTFLoader._Factories[name]) {
  107022. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  107023. return;
  107024. }
  107025. GLTFLoader._Factories[name] = factory;
  107026. // Keep the order of registration so that extensions registered first are called first.
  107027. GLTFLoader._Names.push(name);
  107028. };
  107029. Object.defineProperty(GLTFLoader.prototype, "state", {
  107030. get: function () {
  107031. return this._state;
  107032. },
  107033. enumerable: true,
  107034. configurable: true
  107035. });
  107036. GLTFLoader.prototype.dispose = function () {
  107037. if (this._disposed) {
  107038. return;
  107039. }
  107040. this._disposed = true;
  107041. this.onDisposeObservable.notifyObservers(this);
  107042. this.onDisposeObservable.clear();
  107043. this._clear();
  107044. };
  107045. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  107046. var _this = this;
  107047. return Promise.resolve().then(function () {
  107048. var nodes = null;
  107049. if (meshesNames) {
  107050. var nodeMap_1 = {};
  107051. if (_this._gltf.nodes) {
  107052. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  107053. var node = _a[_i];
  107054. if (node.name) {
  107055. nodeMap_1[node.name] = node;
  107056. }
  107057. }
  107058. }
  107059. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  107060. nodes = names.map(function (name) {
  107061. var node = nodeMap_1[name];
  107062. if (!node) {
  107063. throw new Error("Failed to find node " + name);
  107064. }
  107065. return node;
  107066. });
  107067. }
  107068. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  107069. return {
  107070. meshes: _this._getMeshes(),
  107071. particleSystems: [],
  107072. skeletons: _this._getSkeletons(),
  107073. };
  107074. });
  107075. });
  107076. };
  107077. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  107078. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  107079. };
  107080. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  107081. var _this = this;
  107082. return Promise.resolve().then(function () {
  107083. _this._loadExtensions();
  107084. _this._babylonScene = scene;
  107085. _this._rootUrl = rootUrl;
  107086. _this._progressCallback = onProgress;
  107087. _this._state = BABYLON.GLTFLoaderState.Loading;
  107088. _this._loadData(data);
  107089. _this._checkExtensions();
  107090. var promises = new Array();
  107091. if (nodes) {
  107092. promises.push(_this._loadNodesAsync(nodes));
  107093. }
  107094. else {
  107095. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  107096. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  107097. }
  107098. if (_this.compileMaterials) {
  107099. promises.push(_this._compileMaterialsAsync());
  107100. }
  107101. if (_this.compileShadowGenerators) {
  107102. promises.push(_this._compileShadowGeneratorsAsync());
  107103. }
  107104. return Promise.all(promises).then(function () {
  107105. _this._state = BABYLON.GLTFLoaderState.Ready;
  107106. _this._startAnimations();
  107107. BABYLON.Tools.SetImmediate(function () {
  107108. if (!_this._disposed) {
  107109. Promise.all(_this._completePromises).then(function () {
  107110. _this._state = BABYLON.GLTFLoaderState.Complete;
  107111. _this.onCompleteObservable.notifyObservers(_this);
  107112. _this.onCompleteObservable.clear();
  107113. _this._clear();
  107114. }).catch(function (error) {
  107115. BABYLON.Tools.Error("glTF Loader: " + error.message);
  107116. _this._clear();
  107117. });
  107118. }
  107119. });
  107120. });
  107121. }).catch(function (error) {
  107122. BABYLON.Tools.Error("glTF Loader: " + error.message);
  107123. _this._clear();
  107124. throw error;
  107125. });
  107126. };
  107127. GLTFLoader.prototype._loadExtensions = function () {
  107128. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  107129. var name_1 = _a[_i];
  107130. var extension = GLTFLoader._Factories[name_1](this);
  107131. this._extensions[name_1] = extension;
  107132. this.onExtensionLoadedObservable.notifyObservers(extension);
  107133. }
  107134. this.onExtensionLoadedObservable.clear();
  107135. };
  107136. GLTFLoader.prototype._loadData = function (data) {
  107137. this._gltf = data.json;
  107138. this._setupData();
  107139. if (data.bin) {
  107140. var buffers = this._gltf.buffers;
  107141. if (buffers && buffers[0] && !buffers[0].uri) {
  107142. var binaryBuffer = buffers[0];
  107143. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  107144. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  107145. }
  107146. binaryBuffer._data = Promise.resolve(data.bin);
  107147. }
  107148. else {
  107149. BABYLON.Tools.Warn("Unexpected BIN chunk");
  107150. }
  107151. }
  107152. };
  107153. GLTFLoader.prototype._setupData = function () {
  107154. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  107155. GLTF2.ArrayItem.Assign(this._gltf.animations);
  107156. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  107157. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  107158. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  107159. GLTF2.ArrayItem.Assign(this._gltf.images);
  107160. GLTF2.ArrayItem.Assign(this._gltf.materials);
  107161. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  107162. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  107163. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  107164. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  107165. GLTF2.ArrayItem.Assign(this._gltf.skins);
  107166. GLTF2.ArrayItem.Assign(this._gltf.textures);
  107167. if (this._gltf.nodes) {
  107168. var nodeParents = {};
  107169. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  107170. var node = _a[_i];
  107171. if (node.children) {
  107172. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  107173. var index = _c[_b];
  107174. nodeParents[index] = node._index;
  107175. }
  107176. }
  107177. }
  107178. var rootNode = this._createRootNode();
  107179. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  107180. var node = _e[_d];
  107181. var parentIndex = nodeParents[node._index];
  107182. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  107183. }
  107184. }
  107185. };
  107186. GLTFLoader.prototype._checkExtensions = function () {
  107187. if (this._gltf.extensionsRequired) {
  107188. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  107189. var name_2 = _a[_i];
  107190. var extension = this._extensions[name_2];
  107191. if (!extension || !extension.enabled) {
  107192. throw new Error("Require extension " + name_2 + " is not available");
  107193. }
  107194. }
  107195. }
  107196. };
  107197. GLTFLoader.prototype._createRootNode = function () {
  107198. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  107199. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  107200. switch (this.coordinateSystemMode) {
  107201. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  107202. if (!this._babylonScene.useRightHandedSystem) {
  107203. rootNode.rotation = [0, 1, 0, 0];
  107204. rootNode.scale = [1, 1, -1];
  107205. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  107206. }
  107207. break;
  107208. }
  107209. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  107210. this._babylonScene.useRightHandedSystem = true;
  107211. break;
  107212. }
  107213. default: {
  107214. throw new Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  107215. }
  107216. }
  107217. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  107218. return rootNode;
  107219. };
  107220. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  107221. var promises = new Array();
  107222. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  107223. var node = nodes_1[_i];
  107224. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  107225. }
  107226. promises.push(this._loadAnimationsAsync());
  107227. return Promise.all(promises).then(function () { });
  107228. };
  107229. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  107230. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  107231. if (promise) {
  107232. return promise;
  107233. }
  107234. var promises = new Array();
  107235. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  107236. var index = _a[_i];
  107237. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  107238. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  107239. }
  107240. promises.push(this._loadAnimationsAsync());
  107241. return Promise.all(promises).then(function () { });
  107242. };
  107243. GLTFLoader.prototype._getMeshes = function () {
  107244. var meshes = new Array();
  107245. // Root mesh is always first.
  107246. meshes.push(this._rootBabylonMesh);
  107247. var nodes = this._gltf.nodes;
  107248. if (nodes) {
  107249. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  107250. var node = nodes_2[_i];
  107251. if (node._babylonMesh) {
  107252. meshes.push(node._babylonMesh);
  107253. }
  107254. if (node._primitiveBabylonMeshes) {
  107255. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  107256. var babylonMesh = _b[_a];
  107257. meshes.push(babylonMesh);
  107258. }
  107259. }
  107260. }
  107261. }
  107262. return meshes;
  107263. };
  107264. GLTFLoader.prototype._getSkeletons = function () {
  107265. var skeletons = new Array();
  107266. var skins = this._gltf.skins;
  107267. if (skins) {
  107268. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  107269. var skin = skins_1[_i];
  107270. if (skin._babylonSkeleton) {
  107271. skeletons.push(skin._babylonSkeleton);
  107272. }
  107273. }
  107274. }
  107275. return skeletons;
  107276. };
  107277. GLTFLoader.prototype._startAnimations = function () {
  107278. var animations = this._gltf.animations;
  107279. if (!animations) {
  107280. return;
  107281. }
  107282. switch (this.animationStartMode) {
  107283. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  107284. // do nothing
  107285. break;
  107286. }
  107287. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  107288. var animation = animations[0];
  107289. animation._babylonAnimationGroup.start(true);
  107290. break;
  107291. }
  107292. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  107293. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  107294. var animation = animations_1[_i];
  107295. animation._babylonAnimationGroup.start(true);
  107296. }
  107297. break;
  107298. }
  107299. default: {
  107300. BABYLON.Tools.Error("Invalid animation start mode " + this.animationStartMode);
  107301. return;
  107302. }
  107303. }
  107304. };
  107305. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  107306. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  107307. if (promise) {
  107308. return promise;
  107309. }
  107310. if (node._babylonMesh) {
  107311. throw new Error(context + ": Invalid recursive node hierarchy");
  107312. }
  107313. var promises = new Array();
  107314. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  107315. node._babylonMesh = babylonMesh;
  107316. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  107317. node._babylonAnimationTargets.push(babylonMesh);
  107318. GLTFLoader._LoadTransform(node, babylonMesh);
  107319. if (node.mesh != undefined) {
  107320. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  107321. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh));
  107322. }
  107323. if (node.children) {
  107324. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  107325. var index = _a[_i];
  107326. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  107327. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  107328. }
  107329. }
  107330. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  107331. return Promise.all(promises).then(function () { });
  107332. };
  107333. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh) {
  107334. // TODO: instancing
  107335. var promises = new Array();
  107336. var primitives = mesh.primitives;
  107337. if (!primitives || primitives.length === 0) {
  107338. throw new Error(context + ": Primitives are missing");
  107339. }
  107340. GLTF2.ArrayItem.Assign(primitives);
  107341. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  107342. var primitive = primitives_1[_i];
  107343. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive));
  107344. }
  107345. if (node.skin != undefined) {
  107346. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  107347. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  107348. }
  107349. return Promise.all(promises).then(function () {
  107350. if (node._primitiveBabylonMeshes) {
  107351. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  107352. var primitiveBabylonMesh = _a[_i];
  107353. primitiveBabylonMesh._refreshBoundingInfo(true);
  107354. }
  107355. }
  107356. });
  107357. };
  107358. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive) {
  107359. var _this = this;
  107360. var promises = new Array();
  107361. var babylonMesh = new BABYLON.Mesh((mesh.name || node._babylonMesh.name) + "_" + primitive._index, this._babylonScene, node._babylonMesh);
  107362. babylonMesh.setEnabled(false);
  107363. node._primitiveBabylonMeshes = node._primitiveBabylonMeshes || [];
  107364. node._primitiveBabylonMeshes[primitive._index] = babylonMesh;
  107365. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  107366. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  107367. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  107368. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  107369. }));
  107370. if (primitive.material == undefined) {
  107371. babylonMesh.material = this._getDefaultMaterial();
  107372. }
  107373. else {
  107374. var material = GLTFLoader._GetProperty(context + "/material", this._gltf.materials, primitive.material);
  107375. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh));
  107376. }
  107377. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  107378. return Promise.all(promises).then(function () {
  107379. babylonMesh.setEnabled(true);
  107380. });
  107381. };
  107382. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  107383. var _this = this;
  107384. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  107385. if (promise) {
  107386. return promise;
  107387. }
  107388. var attributes = primitive.attributes;
  107389. if (!attributes) {
  107390. throw new Error(context + ": Attributes are missing");
  107391. }
  107392. if (primitive.mode != undefined && primitive.mode !== 4 /* TRIANGLES */) {
  107393. // TODO: handle other primitive modes
  107394. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  107395. }
  107396. var promises = new Array();
  107397. var babylonVertexData = new BABYLON.VertexData();
  107398. if (primitive.indices == undefined) {
  107399. var positionAccessorIndex = attributes["POSITION"];
  107400. if (positionAccessorIndex != undefined) {
  107401. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  107402. babylonVertexData.indices = new Uint32Array(accessor.count);
  107403. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  107404. babylonVertexData.indices[i] = i;
  107405. }
  107406. }
  107407. }
  107408. else {
  107409. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  107410. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  107411. babylonVertexData.indices = data;
  107412. }));
  107413. }
  107414. var loadAttribute = function (attribute, kind) {
  107415. if (attributes[attribute] == undefined) {
  107416. return;
  107417. }
  107418. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  107419. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  107420. babylonMesh._delayInfo.push(kind);
  107421. }
  107422. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  107423. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  107424. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  107425. if (attribute === "COLOR_0") {
  107426. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  107427. babylonMesh.hasVertexAlpha = true;
  107428. if (accessor.type === "VEC3") {
  107429. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  107430. }
  107431. }
  107432. babylonVertexData.set(attributeData, kind);
  107433. }));
  107434. };
  107435. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  107436. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  107437. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  107438. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  107439. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  107440. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  107441. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  107442. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  107443. return Promise.all(promises).then(function () {
  107444. return babylonVertexData;
  107445. });
  107446. };
  107447. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  107448. if (!primitive.targets) {
  107449. return;
  107450. }
  107451. if (node._numMorphTargets == undefined) {
  107452. node._numMorphTargets = primitive.targets.length;
  107453. }
  107454. else if (primitive.targets.length !== node._numMorphTargets) {
  107455. throw new Error(context + ": Primitives do not have the same number of targets");
  107456. }
  107457. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  107458. for (var index = 0; index < primitive.targets.length; index++) {
  107459. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  107460. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  107461. // TODO: tell the target whether it has positions, normals, tangents
  107462. }
  107463. };
  107464. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  107465. if (!primitive.targets) {
  107466. return Promise.resolve();
  107467. }
  107468. var promises = new Array();
  107469. var morphTargetManager = babylonMesh.morphTargetManager;
  107470. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  107471. var babylonMorphTarget = morphTargetManager.getTarget(index);
  107472. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  107473. }
  107474. return Promise.all(promises).then(function () { });
  107475. };
  107476. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  107477. var _this = this;
  107478. var promises = new Array();
  107479. var loadAttribute = function (attribute, setData) {
  107480. if (attributes[attribute] == undefined) {
  107481. return;
  107482. }
  107483. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  107484. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  107485. setData(data);
  107486. }));
  107487. };
  107488. loadAttribute("POSITION", function (data) {
  107489. if (babylonVertexData.positions) {
  107490. for (var i = 0; i < data.length; i++) {
  107491. data[i] += babylonVertexData.positions[i];
  107492. }
  107493. babylonMorphTarget.setPositions(data);
  107494. }
  107495. });
  107496. loadAttribute("NORMAL", function (data) {
  107497. if (babylonVertexData.normals) {
  107498. for (var i = 0; i < data.length; i++) {
  107499. data[i] += babylonVertexData.normals[i];
  107500. }
  107501. babylonMorphTarget.setNormals(data);
  107502. }
  107503. });
  107504. loadAttribute("TANGENT", function (data) {
  107505. if (babylonVertexData.tangents) {
  107506. // Tangent data for morph targets is stored as xyz delta.
  107507. // The vertexData.tangent is stored as xyzw.
  107508. // So we need to skip every fourth vertexData.tangent.
  107509. for (var i = 0, j = 0; i < data.length; i++) {
  107510. data[i] += babylonVertexData.tangents[j++];
  107511. if ((i + 1) % 3 == 0) {
  107512. j++;
  107513. }
  107514. }
  107515. babylonMorphTarget.setTangents(data);
  107516. }
  107517. });
  107518. return Promise.all(promises).then(function () { });
  107519. };
  107520. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  107521. if (accessor.componentType == 5126 /* FLOAT */) {
  107522. return data;
  107523. }
  107524. var factor = 1;
  107525. if (accessor.normalized) {
  107526. switch (accessor.componentType) {
  107527. case 5121 /* UNSIGNED_BYTE */: {
  107528. factor = 1 / 255;
  107529. break;
  107530. }
  107531. case 5123 /* UNSIGNED_SHORT */: {
  107532. factor = 1 / 65535;
  107533. break;
  107534. }
  107535. default: {
  107536. throw new Error(context + ": Invalid component type " + accessor.componentType);
  107537. }
  107538. }
  107539. }
  107540. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  107541. for (var i = 0; i < result.length; i++) {
  107542. result[i] = data[i] * factor;
  107543. }
  107544. return result;
  107545. };
  107546. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  107547. var result = new Float32Array(data.length / 3 * 4);
  107548. var offset = 0;
  107549. for (var i = 0; i < result.length; i++) {
  107550. if ((i + 1) % 4 === 0) {
  107551. result[i] = 1;
  107552. }
  107553. else {
  107554. result[i] = data[offset++];
  107555. }
  107556. }
  107557. return result;
  107558. };
  107559. GLTFLoader._LoadTransform = function (node, babylonNode) {
  107560. var position = BABYLON.Vector3.Zero();
  107561. var rotation = BABYLON.Quaternion.Identity();
  107562. var scaling = BABYLON.Vector3.One();
  107563. if (node.matrix) {
  107564. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  107565. matrix.decompose(scaling, rotation, position);
  107566. }
  107567. else {
  107568. if (node.translation)
  107569. position = BABYLON.Vector3.FromArray(node.translation);
  107570. if (node.rotation)
  107571. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  107572. if (node.scale)
  107573. scaling = BABYLON.Vector3.FromArray(node.scale);
  107574. }
  107575. babylonNode.position = position;
  107576. babylonNode.rotationQuaternion = rotation;
  107577. babylonNode.scaling = scaling;
  107578. };
  107579. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  107580. var _this = this;
  107581. var assignSkeleton = function () {
  107582. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  107583. var babylonMesh = _a[_i];
  107584. babylonMesh.skeleton = skin._babylonSkeleton;
  107585. }
  107586. node._babylonMesh.parent = _this._rootBabylonMesh;
  107587. node._babylonMesh.position = BABYLON.Vector3.Zero();
  107588. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  107589. node._babylonMesh.scaling = BABYLON.Vector3.One();
  107590. };
  107591. if (skin._loaded) {
  107592. assignSkeleton();
  107593. return skin._loaded;
  107594. }
  107595. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  107596. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  107597. var skeletonId = "skeleton" + skin._index;
  107598. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  107599. skin._babylonSkeleton = babylonSkeleton;
  107600. _this._loadBones(context, skin, inverseBindMatricesData);
  107601. assignSkeleton();
  107602. }));
  107603. };
  107604. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  107605. if (skin.inverseBindMatrices == undefined) {
  107606. return Promise.resolve(null);
  107607. }
  107608. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  107609. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  107610. return data;
  107611. });
  107612. };
  107613. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  107614. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  107615. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  107616. node._babylonAnimationTargets.push(babylonBone);
  107617. return babylonBone;
  107618. };
  107619. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  107620. var babylonBones = {};
  107621. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  107622. var index = _a[_i];
  107623. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  107624. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  107625. }
  107626. };
  107627. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  107628. var babylonBone = babylonBones[node._index];
  107629. if (babylonBone) {
  107630. return babylonBone;
  107631. }
  107632. var boneIndex = skin.joints.indexOf(node._index);
  107633. var baseMatrix = BABYLON.Matrix.Identity();
  107634. if (inverseBindMatricesData && boneIndex !== -1) {
  107635. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  107636. baseMatrix.invertToRef(baseMatrix);
  107637. }
  107638. var babylonParentBone = null;
  107639. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  107640. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  107641. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  107642. }
  107643. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  107644. babylonBones[node._index] = babylonBone;
  107645. return babylonBone;
  107646. };
  107647. GLTFLoader.prototype._getNodeMatrix = function (node) {
  107648. return node.matrix ?
  107649. BABYLON.Matrix.FromArray(node.matrix) :
  107650. 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());
  107651. };
  107652. GLTFLoader.prototype._loadAnimationsAsync = function () {
  107653. var animations = this._gltf.animations;
  107654. if (!animations) {
  107655. return Promise.resolve();
  107656. }
  107657. var promises = new Array();
  107658. for (var index = 0; index < animations.length; index++) {
  107659. var animation = animations[index];
  107660. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  107661. }
  107662. return Promise.all(promises).then(function () { });
  107663. };
  107664. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  107665. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  107666. animation._babylonAnimationGroup = babylonAnimationGroup;
  107667. var promises = new Array();
  107668. GLTF2.ArrayItem.Assign(animation.channels);
  107669. GLTF2.ArrayItem.Assign(animation.samplers);
  107670. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  107671. var channel = _a[_i];
  107672. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  107673. }
  107674. return Promise.all(promises).then(function () {
  107675. babylonAnimationGroup.normalize();
  107676. });
  107677. };
  107678. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  107679. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  107680. if (!targetNode._babylonMesh) {
  107681. return Promise.resolve();
  107682. }
  107683. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  107684. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  107685. var targetPath;
  107686. var animationType;
  107687. switch (channel.target.path) {
  107688. case "translation" /* TRANSLATION */: {
  107689. targetPath = "position";
  107690. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  107691. break;
  107692. }
  107693. case "rotation" /* ROTATION */: {
  107694. targetPath = "rotationQuaternion";
  107695. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  107696. break;
  107697. }
  107698. case "scale" /* SCALE */: {
  107699. targetPath = "scaling";
  107700. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  107701. break;
  107702. }
  107703. case "weights" /* WEIGHTS */: {
  107704. targetPath = "influence";
  107705. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  107706. break;
  107707. }
  107708. default: {
  107709. throw new Error(context + ": Invalid target path " + channel.target.path);
  107710. }
  107711. }
  107712. var outputBufferOffset = 0;
  107713. var getNextOutputValue;
  107714. switch (targetPath) {
  107715. case "position": {
  107716. getNextOutputValue = function () {
  107717. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  107718. outputBufferOffset += 3;
  107719. return value;
  107720. };
  107721. break;
  107722. }
  107723. case "rotationQuaternion": {
  107724. getNextOutputValue = function () {
  107725. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  107726. outputBufferOffset += 4;
  107727. return value;
  107728. };
  107729. break;
  107730. }
  107731. case "scaling": {
  107732. getNextOutputValue = function () {
  107733. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  107734. outputBufferOffset += 3;
  107735. return value;
  107736. };
  107737. break;
  107738. }
  107739. case "influence": {
  107740. getNextOutputValue = function () {
  107741. var value = new Array(targetNode._numMorphTargets);
  107742. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  107743. value[i] = data.output[outputBufferOffset++];
  107744. }
  107745. return value;
  107746. };
  107747. break;
  107748. }
  107749. }
  107750. var getNextKey;
  107751. switch (data.interpolation) {
  107752. case "STEP" /* STEP */: {
  107753. getNextKey = function (frameIndex) { return ({
  107754. frame: data.input[frameIndex],
  107755. value: getNextOutputValue(),
  107756. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  107757. }); };
  107758. break;
  107759. }
  107760. case "LINEAR" /* LINEAR */: {
  107761. getNextKey = function (frameIndex) { return ({
  107762. frame: data.input[frameIndex],
  107763. value: getNextOutputValue()
  107764. }); };
  107765. break;
  107766. }
  107767. case "CUBICSPLINE" /* CUBICSPLINE */: {
  107768. getNextKey = function (frameIndex) { return ({
  107769. frame: data.input[frameIndex],
  107770. inTangent: getNextOutputValue(),
  107771. value: getNextOutputValue(),
  107772. outTangent: getNextOutputValue()
  107773. }); };
  107774. break;
  107775. }
  107776. }
  107777. var keys;
  107778. if (data.input.length === 1) {
  107779. var key = getNextKey(0);
  107780. keys = [
  107781. { frame: key.frame, value: key.value },
  107782. { frame: key.frame + 1, value: key.value }
  107783. ];
  107784. }
  107785. else {
  107786. keys = new Array(data.input.length);
  107787. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  107788. keys[frameIndex] = getNextKey(frameIndex);
  107789. }
  107790. }
  107791. if (targetPath === "influence") {
  107792. var _loop_1 = function (targetIndex) {
  107793. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  107794. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  107795. babylonAnimation.setKeys(keys.map(function (key) { return ({
  107796. frame: key.frame,
  107797. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  107798. value: key.value[targetIndex],
  107799. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  107800. }); }));
  107801. for (var _i = 0, _a = targetNode._primitiveBabylonMeshes; _i < _a.length; _i++) {
  107802. var babylonMesh = _a[_i];
  107803. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  107804. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  107805. }
  107806. };
  107807. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  107808. _loop_1(targetIndex);
  107809. }
  107810. }
  107811. else {
  107812. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  107813. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  107814. babylonAnimation.setKeys(keys);
  107815. if (targetNode._babylonAnimationTargets) {
  107816. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  107817. var target = _a[_i];
  107818. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  107819. }
  107820. }
  107821. }
  107822. });
  107823. };
  107824. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  107825. if (sampler._data) {
  107826. return sampler._data;
  107827. }
  107828. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  107829. switch (interpolation) {
  107830. case "STEP" /* STEP */:
  107831. case "LINEAR" /* LINEAR */:
  107832. case "CUBICSPLINE" /* CUBICSPLINE */: {
  107833. break;
  107834. }
  107835. default: {
  107836. throw new Error(context + ": Invalid interpolation " + sampler.interpolation);
  107837. }
  107838. }
  107839. var inputData;
  107840. var outputData;
  107841. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  107842. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  107843. sampler._data = Promise.all([
  107844. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  107845. inputData = data;
  107846. }),
  107847. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  107848. outputData = data;
  107849. })
  107850. ]).then(function () {
  107851. return {
  107852. input: inputData,
  107853. interpolation: interpolation,
  107854. output: outputData,
  107855. };
  107856. });
  107857. return sampler._data;
  107858. };
  107859. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  107860. if (buffer._data) {
  107861. return buffer._data;
  107862. }
  107863. if (!buffer.uri) {
  107864. throw new Error(context + ": Uri is missing");
  107865. }
  107866. buffer._data = this._loadUriAsync(context, buffer.uri);
  107867. return buffer._data;
  107868. };
  107869. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  107870. if (bufferView._data) {
  107871. return bufferView._data;
  107872. }
  107873. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  107874. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  107875. try {
  107876. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  107877. }
  107878. catch (e) {
  107879. throw new Error(context + ": " + e.message);
  107880. }
  107881. });
  107882. return bufferView._data;
  107883. };
  107884. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  107885. var _this = this;
  107886. if (accessor.sparse) {
  107887. throw new Error(context + ": Sparse accessors are not currently supported");
  107888. }
  107889. if (accessor._data) {
  107890. return accessor._data;
  107891. }
  107892. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  107893. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  107894. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  107895. var byteOffset = accessor.byteOffset || 0;
  107896. var byteStride = bufferView.byteStride;
  107897. if (byteStride === 0) {
  107898. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  107899. }
  107900. try {
  107901. switch (accessor.componentType) {
  107902. case 5120 /* BYTE */: {
  107903. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  107904. }
  107905. case 5121 /* UNSIGNED_BYTE */: {
  107906. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  107907. }
  107908. case 5122 /* SHORT */: {
  107909. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  107910. }
  107911. case 5123 /* UNSIGNED_SHORT */: {
  107912. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  107913. }
  107914. case 5125 /* UNSIGNED_INT */: {
  107915. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  107916. }
  107917. case 5126 /* FLOAT */: {
  107918. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  107919. }
  107920. default: {
  107921. throw new Error(context + ": Invalid component type " + accessor.componentType);
  107922. }
  107923. }
  107924. }
  107925. catch (e) {
  107926. throw new Error(context + ": " + e);
  107927. }
  107928. });
  107929. return accessor._data;
  107930. };
  107931. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  107932. byteOffset += data.byteOffset;
  107933. var targetLength = count * numComponents;
  107934. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  107935. return new typedArray(data.buffer, byteOffset, targetLength);
  107936. }
  107937. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  107938. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  107939. var targetBuffer = new typedArray(targetLength);
  107940. var sourceIndex = 0;
  107941. var targetIndex = 0;
  107942. while (targetIndex < targetLength) {
  107943. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  107944. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  107945. targetIndex++;
  107946. }
  107947. sourceIndex += elementStride;
  107948. }
  107949. return targetBuffer;
  107950. };
  107951. GLTFLoader.prototype._getDefaultMaterial = function () {
  107952. var id = "__gltf_default";
  107953. var babylonMaterial = this._babylonScene.getMaterialByName(id);
  107954. if (!babylonMaterial) {
  107955. babylonMaterial = new BABYLON.PBRMaterial(id, this._babylonScene);
  107956. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  107957. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  107958. babylonMaterial.metallic = 1;
  107959. babylonMaterial.roughness = 1;
  107960. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  107961. }
  107962. return babylonMaterial;
  107963. };
  107964. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material) {
  107965. var promises = new Array();
  107966. var babylonMaterial = material._babylonMaterial;
  107967. // Ensure metallic workflow
  107968. babylonMaterial.metallic = 1;
  107969. babylonMaterial.roughness = 1;
  107970. var properties = material.pbrMetallicRoughness;
  107971. if (properties) {
  107972. if (properties.baseColorFactor) {
  107973. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  107974. babylonMaterial.alpha = properties.baseColorFactor[3];
  107975. }
  107976. else {
  107977. babylonMaterial.albedoColor = BABYLON.Color3.White();
  107978. }
  107979. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  107980. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  107981. if (properties.baseColorTexture) {
  107982. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  107983. babylonMaterial.albedoTexture = texture;
  107984. }));
  107985. }
  107986. if (properties.metallicRoughnessTexture) {
  107987. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  107988. babylonMaterial.metallicTexture = texture;
  107989. }));
  107990. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  107991. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  107992. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  107993. }
  107994. }
  107995. this._loadMaterialAlphaProperties(context, material);
  107996. return Promise.all(promises).then(function () { });
  107997. };
  107998. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  107999. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh);
  108000. if (promise) {
  108001. return promise;
  108002. }
  108003. material._babylonMeshes = material._babylonMeshes || [];
  108004. material._babylonMeshes.push(babylonMesh);
  108005. if (material._loaded) {
  108006. babylonMesh.material = material._babylonMaterial;
  108007. return material._loaded;
  108008. }
  108009. var promises = new Array();
  108010. var babylonMaterial = this._createMaterial(material);
  108011. material._babylonMaterial = babylonMaterial;
  108012. promises.push(this._loadMaterialBasePropertiesAsync(context, material));
  108013. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material));
  108014. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  108015. babylonMesh.material = babylonMaterial;
  108016. return (material._loaded = Promise.all(promises).then(function () { }));
  108017. };
  108018. GLTFLoader.prototype._createMaterial = function (material) {
  108019. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "material" + material._index, this._babylonScene);
  108020. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  108021. return babylonMaterial;
  108022. };
  108023. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material) {
  108024. var promises = new Array();
  108025. var babylonMaterial = material._babylonMaterial;
  108026. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  108027. if (material.doubleSided) {
  108028. babylonMaterial.backFaceCulling = false;
  108029. babylonMaterial.twoSidedLighting = true;
  108030. }
  108031. if (material.normalTexture) {
  108032. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  108033. babylonMaterial.bumpTexture = texture;
  108034. }));
  108035. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  108036. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  108037. if (material.normalTexture.scale != undefined) {
  108038. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  108039. }
  108040. }
  108041. if (material.occlusionTexture) {
  108042. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  108043. babylonMaterial.ambientTexture = texture;
  108044. }));
  108045. babylonMaterial.useAmbientInGrayScale = true;
  108046. if (material.occlusionTexture.strength != undefined) {
  108047. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  108048. }
  108049. }
  108050. if (material.emissiveTexture) {
  108051. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  108052. babylonMaterial.emissiveTexture = texture;
  108053. }));
  108054. }
  108055. return Promise.all(promises).then(function () { });
  108056. };
  108057. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material) {
  108058. var babylonMaterial = material._babylonMaterial;
  108059. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  108060. switch (alphaMode) {
  108061. case "OPAQUE" /* OPAQUE */: {
  108062. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  108063. break;
  108064. }
  108065. case "MASK" /* MASK */: {
  108066. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  108067. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  108068. if (babylonMaterial.alpha) {
  108069. if (babylonMaterial.alpha === 0) {
  108070. babylonMaterial.alphaCutOff = 1;
  108071. }
  108072. else {
  108073. babylonMaterial.alphaCutOff /= babylonMaterial.alpha;
  108074. }
  108075. babylonMaterial.alpha = 1;
  108076. }
  108077. if (babylonMaterial.albedoTexture) {
  108078. babylonMaterial.albedoTexture.hasAlpha = true;
  108079. }
  108080. break;
  108081. }
  108082. case "BLEND" /* BLEND */: {
  108083. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  108084. if (babylonMaterial.albedoTexture) {
  108085. babylonMaterial.albedoTexture.hasAlpha = true;
  108086. babylonMaterial.useAlphaFromAlbedoTexture = true;
  108087. }
  108088. break;
  108089. }
  108090. default: {
  108091. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  108092. }
  108093. }
  108094. };
  108095. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  108096. var _this = this;
  108097. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  108098. context = "#/textures/" + textureInfo.index;
  108099. var promises = new Array();
  108100. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  108101. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  108102. var deferred = new BABYLON.Deferred();
  108103. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  108104. if (!_this._disposed) {
  108105. deferred.resolve();
  108106. }
  108107. }, function (message, exception) {
  108108. if (!_this._disposed) {
  108109. deferred.reject(new Error(context + ": " + (exception && exception.message) ? exception.message : message || "Failed to load texture"));
  108110. }
  108111. });
  108112. promises.push(deferred.promise);
  108113. babylonTexture.name = texture.name || "texture" + texture._index;
  108114. babylonTexture.wrapU = samplerData.wrapU;
  108115. babylonTexture.wrapV = samplerData.wrapV;
  108116. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  108117. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  108118. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  108119. babylonTexture.updateURL(objectURL);
  108120. }));
  108121. assign(babylonTexture);
  108122. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  108123. return Promise.all(promises).then(function () { });
  108124. };
  108125. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  108126. if (!sampler._data) {
  108127. sampler._data = {
  108128. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  108129. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  108130. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  108131. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  108132. };
  108133. }
  108134. ;
  108135. return sampler._data;
  108136. };
  108137. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  108138. if (image._objectURL) {
  108139. return image._objectURL;
  108140. }
  108141. var promise;
  108142. if (image.uri) {
  108143. promise = this._loadUriAsync(context, image.uri);
  108144. }
  108145. else {
  108146. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  108147. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  108148. }
  108149. image._objectURL = promise.then(function (data) {
  108150. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  108151. });
  108152. return image._objectURL;
  108153. };
  108154. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  108155. var _this = this;
  108156. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  108157. if (promise) {
  108158. return promise;
  108159. }
  108160. if (!GLTFLoader._ValidateUri(uri)) {
  108161. throw new Error(context + ": Uri '" + uri + "' is invalid");
  108162. }
  108163. if (BABYLON.Tools.IsBase64(uri)) {
  108164. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  108165. }
  108166. return new Promise(function (resolve, reject) {
  108167. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  108168. if (!_this._disposed) {
  108169. resolve(new Uint8Array(data));
  108170. }
  108171. }, function (event) {
  108172. if (!_this._disposed) {
  108173. try {
  108174. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  108175. request._lengthComputable = event.lengthComputable;
  108176. request._loaded = event.loaded;
  108177. request._total = event.total;
  108178. _this._onProgress();
  108179. }
  108180. }
  108181. catch (e) {
  108182. reject(e);
  108183. }
  108184. }
  108185. }, _this._babylonScene.database, true, function (request, exception) {
  108186. if (!_this._disposed) {
  108187. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  108188. }
  108189. });
  108190. _this._requests.push(request);
  108191. });
  108192. };
  108193. GLTFLoader.prototype._onProgress = function () {
  108194. if (!this._progressCallback) {
  108195. return;
  108196. }
  108197. var lengthComputable = true;
  108198. var loaded = 0;
  108199. var total = 0;
  108200. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  108201. var request = _a[_i];
  108202. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  108203. return;
  108204. }
  108205. lengthComputable = lengthComputable && request._lengthComputable;
  108206. loaded += request._loaded;
  108207. total += request._total;
  108208. }
  108209. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  108210. };
  108211. GLTFLoader._GetProperty = function (context, array, index) {
  108212. if (!array || index == undefined || !array[index]) {
  108213. throw new Error(context + ": Failed to find index " + index);
  108214. }
  108215. return array[index];
  108216. };
  108217. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  108218. // Set defaults if undefined
  108219. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  108220. switch (mode) {
  108221. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  108222. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  108223. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  108224. default:
  108225. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  108226. return BABYLON.Texture.WRAP_ADDRESSMODE;
  108227. }
  108228. };
  108229. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  108230. // Set defaults if undefined
  108231. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  108232. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  108233. if (magFilter === 9729 /* LINEAR */) {
  108234. switch (minFilter) {
  108235. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  108236. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  108237. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  108238. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  108239. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  108240. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  108241. default:
  108242. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  108243. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  108244. }
  108245. }
  108246. else {
  108247. if (magFilter !== 9728 /* NEAREST */) {
  108248. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  108249. }
  108250. switch (minFilter) {
  108251. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  108252. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  108253. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  108254. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  108255. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  108256. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  108257. default:
  108258. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  108259. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  108260. }
  108261. }
  108262. };
  108263. GLTFLoader._GetNumComponents = function (context, type) {
  108264. switch (type) {
  108265. case "SCALAR": return 1;
  108266. case "VEC2": return 2;
  108267. case "VEC3": return 3;
  108268. case "VEC4": return 4;
  108269. case "MAT2": return 4;
  108270. case "MAT3": return 9;
  108271. case "MAT4": return 16;
  108272. }
  108273. throw new Error(context + ": Invalid type " + type);
  108274. };
  108275. GLTFLoader._ValidateUri = function (uri) {
  108276. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  108277. };
  108278. GLTFLoader.prototype._compileMaterialsAsync = function () {
  108279. var promises = new Array();
  108280. if (this._gltf.materials) {
  108281. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  108282. var material = _a[_i];
  108283. var babylonMaterial = material._babylonMaterial;
  108284. var babylonMeshes = material._babylonMeshes;
  108285. if (babylonMaterial && babylonMeshes) {
  108286. for (var _b = 0, babylonMeshes_1 = babylonMeshes; _b < babylonMeshes_1.length; _b++) {
  108287. var babylonMesh = babylonMeshes_1[_b];
  108288. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  108289. if (this.useClipPlane) {
  108290. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  108291. }
  108292. }
  108293. }
  108294. }
  108295. }
  108296. return Promise.all(promises).then(function () { });
  108297. };
  108298. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  108299. var promises = new Array();
  108300. var lights = this._babylonScene.lights;
  108301. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  108302. var light = lights_1[_i];
  108303. var generator = light.getShadowGenerator();
  108304. if (generator) {
  108305. promises.push(generator.forceCompilationAsync());
  108306. }
  108307. }
  108308. return Promise.all(promises).then(function () { });
  108309. };
  108310. GLTFLoader.prototype._clear = function () {
  108311. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  108312. var request = _a[_i];
  108313. request.abort();
  108314. }
  108315. this._requests.length = 0;
  108316. if (this._gltf && this._gltf.images) {
  108317. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  108318. var image = _c[_b];
  108319. if (image._objectURL) {
  108320. image._objectURL.then(function (value) {
  108321. URL.revokeObjectURL(value);
  108322. });
  108323. image._objectURL = undefined;
  108324. }
  108325. }
  108326. }
  108327. delete this._gltf;
  108328. delete this._babylonScene;
  108329. this._completePromises.length = 0;
  108330. for (var name_3 in this._extensions) {
  108331. this._extensions[name_3].dispose();
  108332. }
  108333. this._extensions = {};
  108334. delete this._rootBabylonMesh;
  108335. delete this._progressCallback;
  108336. this.onMeshLoadedObservable.clear();
  108337. this.onTextureLoadedObservable.clear();
  108338. this.onMaterialLoadedObservable.clear();
  108339. };
  108340. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  108341. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  108342. var name_4 = _a[_i];
  108343. var extension = this._extensions[name_4];
  108344. if (extension.enabled) {
  108345. var promise = actionAsync(extension);
  108346. if (promise) {
  108347. return promise;
  108348. }
  108349. }
  108350. }
  108351. return null;
  108352. };
  108353. GLTFLoader._Names = new Array();
  108354. GLTFLoader._Factories = {};
  108355. return GLTFLoader;
  108356. }());
  108357. GLTF2.GLTFLoader = GLTFLoader;
  108358. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  108359. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  108360. })(BABYLON || (BABYLON = {}));
  108361. //# sourceMappingURL=babylon.glTFLoader.js.map
  108362. var BABYLON;
  108363. (function (BABYLON) {
  108364. var GLTF2;
  108365. (function (GLTF2) {
  108366. var GLTFLoaderExtension = /** @class */ (function () {
  108367. function GLTFLoaderExtension(loader) {
  108368. this.enabled = true;
  108369. this._loader = loader;
  108370. }
  108371. GLTFLoaderExtension.prototype.dispose = function () {
  108372. delete this._loader;
  108373. };
  108374. // #region Overridable Methods
  108375. /** Override this method to modify the default behavior for loading scenes. */
  108376. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  108377. /** Override this method to modify the default behavior for loading nodes. */
  108378. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  108379. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  108380. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  108381. /** Override this method to modify the default behavior for loading materials. */
  108382. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh) { return null; };
  108383. /** Override this method to modify the default behavior for loading uris. */
  108384. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  108385. // #endregion
  108386. /** Helper method called by a loader extension to load an glTF extension. */
  108387. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  108388. if (!property.extensions) {
  108389. return null;
  108390. }
  108391. var extensions = property.extensions;
  108392. var extension = extensions[this.name];
  108393. if (!extension) {
  108394. return null;
  108395. }
  108396. // Clear out the extension before executing the action to avoid recursing into the same property.
  108397. delete extensions[this.name];
  108398. try {
  108399. return actionAsync(context + "/extensions/" + this.name, extension);
  108400. }
  108401. finally {
  108402. // Restore the extension after executing the action.
  108403. extensions[this.name] = extension;
  108404. }
  108405. };
  108406. /** Helper method called by the loader to allow extensions to override loading scenes. */
  108407. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  108408. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  108409. };
  108410. /** Helper method called by the loader to allow extensions to override loading nodes. */
  108411. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  108412. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  108413. };
  108414. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  108415. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  108416. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  108417. };
  108418. /** Helper method called by the loader to allow extensions to override loading materials. */
  108419. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh) {
  108420. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh); });
  108421. };
  108422. /** Helper method called by the loader to allow extensions to override loading uris. */
  108423. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  108424. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  108425. };
  108426. return GLTFLoaderExtension;
  108427. }());
  108428. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  108429. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  108430. })(BABYLON || (BABYLON = {}));
  108431. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  108432. var BABYLON;
  108433. (function (BABYLON) {
  108434. var GLTF2;
  108435. (function (GLTF2) {
  108436. var Extensions;
  108437. (function (Extensions) {
  108438. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  108439. var NAME = "MSFT_lod";
  108440. var MSFT_lod = /** @class */ (function (_super) {
  108441. __extends(MSFT_lod, _super);
  108442. function MSFT_lod() {
  108443. var _this = _super !== null && _super.apply(this, arguments) || this;
  108444. _this.name = NAME;
  108445. /**
  108446. * Maximum number of LODs to load, starting from the lowest LOD.
  108447. */
  108448. _this.maxLODsToLoad = Number.MAX_VALUE;
  108449. _this._loadingNodeLOD = null;
  108450. _this._loadNodeSignals = {};
  108451. _this._loadingMaterialLOD = null;
  108452. _this._loadMaterialSignals = {};
  108453. return _this;
  108454. }
  108455. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  108456. var _this = this;
  108457. return this._loadExtensionAsync(context, node, function (context, extension) {
  108458. var firstPromise;
  108459. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  108460. var _loop_1 = function (indexLOD) {
  108461. var nodeLOD = nodeLODs[indexLOD];
  108462. if (indexLOD !== 0) {
  108463. _this._loadingNodeLOD = nodeLOD;
  108464. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  108465. }
  108466. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  108467. if (indexLOD !== 0) {
  108468. var previousNodeLOD = nodeLODs[indexLOD - 1];
  108469. previousNodeLOD._babylonMesh.setEnabled(false);
  108470. }
  108471. if (indexLOD !== nodeLODs.length - 1) {
  108472. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  108473. _this._loadNodeSignals[nodeIndex].resolve();
  108474. delete _this._loadNodeSignals[nodeIndex];
  108475. }
  108476. });
  108477. if (indexLOD === 0) {
  108478. firstPromise = promise;
  108479. }
  108480. else {
  108481. _this._loader._completePromises.push(promise);
  108482. _this._loadingNodeLOD = null;
  108483. }
  108484. };
  108485. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  108486. _loop_1(indexLOD);
  108487. }
  108488. return firstPromise;
  108489. });
  108490. };
  108491. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  108492. var _this = this;
  108493. // Don't load material LODs if already loading a node LOD.
  108494. if (this._loadingNodeLOD) {
  108495. return null;
  108496. }
  108497. return this._loadExtensionAsync(context, material, function (context, extension) {
  108498. var firstPromise;
  108499. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  108500. var _loop_2 = function (indexLOD) {
  108501. var materialLOD = materialLODs[indexLOD];
  108502. if (indexLOD !== 0) {
  108503. _this._loadingMaterialLOD = materialLOD;
  108504. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  108505. }
  108506. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh).then(function () {
  108507. if (indexLOD !== materialLODs.length - 1) {
  108508. var materialIndex = materialLODs[indexLOD + 1]._index;
  108509. _this._loadMaterialSignals[materialIndex].resolve();
  108510. delete _this._loadMaterialSignals[materialIndex];
  108511. }
  108512. });
  108513. if (indexLOD === 0) {
  108514. firstPromise = promise;
  108515. }
  108516. else {
  108517. _this._loader._completePromises.push(promise);
  108518. _this._loadingMaterialLOD = null;
  108519. }
  108520. };
  108521. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  108522. _loop_2(indexLOD);
  108523. }
  108524. return firstPromise;
  108525. });
  108526. };
  108527. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  108528. var _this = this;
  108529. // Defer the loading of uris if loading a material or node LOD.
  108530. if (this._loadingMaterialLOD) {
  108531. var index = this._loadingMaterialLOD._index;
  108532. return this._loadMaterialSignals[index].promise.then(function () {
  108533. return _this._loader._loadUriAsync(context, uri);
  108534. });
  108535. }
  108536. else if (this._loadingNodeLOD) {
  108537. var index = this._loadingNodeLOD._index;
  108538. return this._loadNodeSignals[index].promise.then(function () {
  108539. return _this._loader._loadUriAsync(context, uri);
  108540. });
  108541. }
  108542. return null;
  108543. };
  108544. /**
  108545. * Gets an array of LOD properties from lowest to highest.
  108546. */
  108547. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  108548. if (this.maxLODsToLoad <= 0) {
  108549. throw new Error("maxLODsToLoad must be greater than zero");
  108550. }
  108551. var properties = new Array();
  108552. for (var i = ids.length - 1; i >= 0; i--) {
  108553. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  108554. if (properties.length === this.maxLODsToLoad) {
  108555. return properties;
  108556. }
  108557. }
  108558. properties.push(property);
  108559. return properties;
  108560. };
  108561. return MSFT_lod;
  108562. }(GLTF2.GLTFLoaderExtension));
  108563. Extensions.MSFT_lod = MSFT_lod;
  108564. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  108565. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  108566. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  108567. })(BABYLON || (BABYLON = {}));
  108568. //# sourceMappingURL=MSFT_lod.js.map
  108569. var BABYLON;
  108570. (function (BABYLON) {
  108571. var GLTF2;
  108572. (function (GLTF2) {
  108573. var Extensions;
  108574. (function (Extensions) {
  108575. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  108576. var NAME = "KHR_draco_mesh_compression";
  108577. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  108578. __extends(KHR_draco_mesh_compression, _super);
  108579. function KHR_draco_mesh_compression(loader) {
  108580. var _this = _super.call(this, loader) || this;
  108581. _this.name = NAME;
  108582. _this._dracoCompression = null;
  108583. // Disable extension if decoder is not available.
  108584. if (!BABYLON.DracoCompression.DecoderUrl) {
  108585. _this.enabled = false;
  108586. }
  108587. return _this;
  108588. }
  108589. KHR_draco_mesh_compression.prototype.dispose = function () {
  108590. if (this._dracoCompression) {
  108591. this._dracoCompression.dispose();
  108592. }
  108593. _super.prototype.dispose.call(this);
  108594. };
  108595. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  108596. var _this = this;
  108597. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  108598. if (primitive.mode != undefined) {
  108599. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  108600. primitive.mode !== 4 /* TRIANGLES */) {
  108601. throw new Error(context + ": Unsupported mode " + primitive.mode);
  108602. }
  108603. // TODO: handle triangle strips
  108604. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  108605. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  108606. }
  108607. }
  108608. var attributes = {};
  108609. var loadAttribute = function (name, kind) {
  108610. var uniqueId = extension.attributes[name];
  108611. if (uniqueId == undefined) {
  108612. return;
  108613. }
  108614. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  108615. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  108616. babylonMesh._delayInfo.push(kind);
  108617. }
  108618. attributes[kind] = uniqueId;
  108619. };
  108620. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  108621. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  108622. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  108623. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  108624. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  108625. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  108626. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  108627. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  108628. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  108629. return _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  108630. try {
  108631. if (!_this._dracoCompression) {
  108632. _this._dracoCompression = new BABYLON.DracoCompression();
  108633. }
  108634. return _this._dracoCompression.decodeMeshAsync(data, attributes);
  108635. }
  108636. catch (e) {
  108637. throw new Error(context + ": " + e.message);
  108638. }
  108639. });
  108640. });
  108641. };
  108642. return KHR_draco_mesh_compression;
  108643. }(GLTF2.GLTFLoaderExtension));
  108644. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  108645. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  108646. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  108647. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  108648. })(BABYLON || (BABYLON = {}));
  108649. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  108650. var BABYLON;
  108651. (function (BABYLON) {
  108652. var GLTF2;
  108653. (function (GLTF2) {
  108654. var Extensions;
  108655. (function (Extensions) {
  108656. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  108657. var NAME = "KHR_materials_pbrSpecularGlossiness";
  108658. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  108659. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  108660. function KHR_materials_pbrSpecularGlossiness() {
  108661. var _this = _super !== null && _super.apply(this, arguments) || this;
  108662. _this.name = NAME;
  108663. return _this;
  108664. }
  108665. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  108666. var _this = this;
  108667. return this._loadExtensionAsync(context, material, function (context, extension) {
  108668. material._babylonMeshes = material._babylonMeshes || [];
  108669. material._babylonMeshes.push(babylonMesh);
  108670. if (material._loaded) {
  108671. babylonMesh.material = material._babylonMaterial;
  108672. return material._loaded;
  108673. }
  108674. var promises = new Array();
  108675. var babylonMaterial = _this._loader._createMaterial(material);
  108676. material._babylonMaterial = babylonMaterial;
  108677. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material));
  108678. promises.push(_this._loadSpecularGlossinessPropertiesAsync(_this._loader, context, material, extension));
  108679. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  108680. babylonMesh.material = babylonMaterial;
  108681. return (material._loaded = Promise.all(promises).then(function () { }));
  108682. });
  108683. };
  108684. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (loader, context, material, properties) {
  108685. var promises = new Array();
  108686. var babylonMaterial = material._babylonMaterial;
  108687. if (properties.diffuseFactor) {
  108688. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  108689. babylonMaterial.alpha = properties.diffuseFactor[3];
  108690. }
  108691. else {
  108692. babylonMaterial.albedoColor = BABYLON.Color3.White();
  108693. }
  108694. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  108695. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  108696. if (properties.diffuseTexture) {
  108697. promises.push(loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  108698. babylonMaterial.albedoTexture = texture;
  108699. }));
  108700. }
  108701. if (properties.specularGlossinessTexture) {
  108702. promises.push(loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  108703. babylonMaterial.reflectivityTexture = texture;
  108704. }));
  108705. babylonMaterial.reflectivityTexture.hasAlpha = true;
  108706. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  108707. }
  108708. loader._loadMaterialAlphaProperties(context, material);
  108709. return Promise.all(promises).then(function () { });
  108710. };
  108711. return KHR_materials_pbrSpecularGlossiness;
  108712. }(GLTF2.GLTFLoaderExtension));
  108713. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  108714. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  108715. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  108716. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  108717. })(BABYLON || (BABYLON = {}));
  108718. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  108719. var BABYLON;
  108720. (function (BABYLON) {
  108721. var GLTF2;
  108722. (function (GLTF2) {
  108723. var Extensions;
  108724. (function (Extensions) {
  108725. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  108726. var NAME = "KHR_lights";
  108727. var LightType;
  108728. (function (LightType) {
  108729. LightType["AMBIENT"] = "ambient";
  108730. LightType["DIRECTIONAL"] = "directional";
  108731. LightType["POINT"] = "point";
  108732. LightType["SPOT"] = "spot";
  108733. })(LightType || (LightType = {}));
  108734. var KHR_lights = /** @class */ (function (_super) {
  108735. __extends(KHR_lights, _super);
  108736. function KHR_lights() {
  108737. var _this = _super !== null && _super.apply(this, arguments) || this;
  108738. _this.name = NAME;
  108739. return _this;
  108740. }
  108741. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  108742. var _this = this;
  108743. return this._loadExtensionAsync(context, scene, function (context, extension) {
  108744. var promise = _this._loader._loadSceneAsync(context, scene);
  108745. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  108746. if (light.type !== LightType.AMBIENT) {
  108747. throw new Error(context + ": Only ambient lights are allowed on a scene");
  108748. }
  108749. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  108750. return promise;
  108751. });
  108752. };
  108753. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  108754. var _this = this;
  108755. return this._loadExtensionAsync(context, node, function (context, extension) {
  108756. var promise = _this._loader._loadNodeAsync(context, node);
  108757. var babylonLight;
  108758. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  108759. var name = node._babylonMesh.name;
  108760. switch (light.type) {
  108761. case LightType.AMBIENT: {
  108762. throw new Error(context + ": Ambient lights are not allowed on a node");
  108763. }
  108764. case LightType.DIRECTIONAL: {
  108765. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  108766. break;
  108767. }
  108768. case LightType.POINT: {
  108769. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  108770. break;
  108771. }
  108772. case LightType.SPOT: {
  108773. var spotLight = light;
  108774. // TODO: support inner and outer cone angles
  108775. //const innerConeAngle = spotLight.innerConeAngle || 0;
  108776. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  108777. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  108778. break;
  108779. }
  108780. default: {
  108781. throw new Error(context + ": Invalid light type " + light.type);
  108782. }
  108783. }
  108784. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  108785. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  108786. babylonLight.parent = node._babylonMesh;
  108787. return promise;
  108788. });
  108789. };
  108790. Object.defineProperty(KHR_lights.prototype, "_lights", {
  108791. get: function () {
  108792. var extensions = this._loader._gltf.extensions;
  108793. if (!extensions || !extensions[this.name]) {
  108794. throw new Error("#/extensions: " + this.name + " not found");
  108795. }
  108796. var extension = extensions[this.name];
  108797. return extension.lights;
  108798. },
  108799. enumerable: true,
  108800. configurable: true
  108801. });
  108802. return KHR_lights;
  108803. }(GLTF2.GLTFLoaderExtension));
  108804. Extensions.KHR_lights = KHR_lights;
  108805. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  108806. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  108807. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  108808. })(BABYLON || (BABYLON = {}));
  108809. //# sourceMappingURL=KHR_lights.js.map
  108810. (function universalModuleDefinition(root, factory) {
  108811. var f = factory();
  108812. if(true)
  108813. module.exports = f;
  108814. else if(typeof define === 'function' && define.amd)
  108815. define("babylonjs-loaders", ["BABYLON"], factory);
  108816. else if(typeof exports === 'object')
  108817. exports["babylonjs-loaders"] = f;
  108818. else {
  108819. root["BABYLON"] = f;
  108820. }
  108821. })(this, function() {
  108822. return BABYLON;
  108823. });
  108824. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2)))
  108825. /***/ }),
  108826. /* 31 */
  108827. /***/ (function(module, exports, __webpack_require__) {
  108828. /*!
  108829. * PEP v0.4.3 | https://github.com/jquery/PEP
  108830. * Copyright jQuery Foundation and other contributors | http://jquery.org/license
  108831. */
  108832. !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);
  108833. // define inherited MouseEvent properties
  108834. // skip bubbles and cancelable since they're set above in initEvent()
  108835. for(var d,e=2;e<m.length;e++)d=m[e],c[d]=b[d]||n[e];c.buttons=b.buttons||0;
  108836. // Spec requires that pointers without pressure specified use 0.5 for down
  108837. // state and 0 for up state.
  108838. var f=0;
  108839. // add x/y properties aliased to clientX/Y
  108840. // define the properties of the PointerEvent interface
  108841. 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(){
  108842. // only activate if this platform does not have pointer events
  108843. 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}})}/**
  108844. * This is the constructor for new PointerEvents.
  108845. *
  108846. * New Pointer Events must be given a type, and an optional dictionary of
  108847. * initialization properties.
  108848. *
  108849. * Due to certain platform requirements, events returned from the constructor
  108850. * identify as MouseEvents.
  108851. *
  108852. * @constructor
  108853. * @param {String} inType The type of the event to create.
  108854. * @param {Object} [inDict] An optional dictionary of initial event properties.
  108855. * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`.
  108856. */
  108857. 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},
  108858. // return value, key, map
  108859. forEach:function(a,b){return this.array.forEach(function(c,d){a.call(b,c,d,this)},this)}};var q=[
  108860. // MouseEvent
  108861. "bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget",
  108862. // DOM Level 3
  108863. "buttons",
  108864. // PointerEvent
  108865. "pointerId","width","height","pressure","tiltX","tiltY","pointerType","hwTimestamp","isPrimary",
  108866. // event instance
  108867. "type","target","currentTarget","which","pageX","pageY","timeStamp"],r=[
  108868. // MouseEvent
  108869. !1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,
  108870. // DOM Level 3
  108871. 0,
  108872. // PointerEvent
  108873. 0,0,0,0,0,0,"",0,!1,
  108874. // event instance
  108875. "",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),
  108876. // Scope objects for native events.
  108877. // This exists for ease of testing.
  108878. eventSources:Object.create(null),eventSourceList:[],/**
  108879. * Add a new event source that will generate pointer events.
  108880. *
  108881. * `inSource` must contain an array of event names named `events`, and
  108882. * functions with the names specified in the `events` array.
  108883. * @param {string} name A name for the event source
  108884. * @param {Object} source A new source of platform events.
  108885. */
  108886. 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++)
  108887. // call eventsource register
  108888. b.register.call(b,a)},unregister:function(a){for(var b,c=this.eventSourceList.length,d=0;d<c&&(b=this.eventSourceList[d]);d++)
  108889. // call eventsource register
  108890. b.unregister.call(b,a)},contains:/*scope.external.contains || */function(a,b){try{return a.contains(b)}catch(c){
  108891. // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
  108892. return!1}},
  108893. // EVENTS
  108894. 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)},
  108895. // LISTENER LOGIC
  108896. eventHandler:function(a){
  108897. // This is used to prevent multiple dispatch of pointerevents from
  108898. // platform events. This can happen when two elements in different scopes
  108899. // are set up to create pointer events, which is relevant to Shadow DOM.
  108900. if(!a._handledByPE){var b=a.type,c=this.eventMap&&this.eventMap[b];c&&c(a),a._handledByPE=!0}},
  108901. // set up event listeners
  108902. listen:function(a,b){b.forEach(function(b){this.addEvent(a,b)},this)},
  108903. // remove event listeners
  108904. 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)},
  108905. // EVENT CREATION AND TRACKING
  108906. /**
  108907. * Creates a new Event of type `inType`, based on the information in
  108908. * `inEvent`.
  108909. *
  108910. * @param {string} inType A string representing the type of event to create
  108911. * @param {Event} inEvent A platform event with a target
  108912. * @return {Event} A PointerEvent of type `inType`
  108913. */
  108914. makeEvent:function(b,c){
  108915. // relatedTarget must be null if pointer is captured
  108916. 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},
  108917. // make and dispatch an event in one call
  108918. fireEvent:function(a,b){var c=this.makeEvent(a,b);return this.dispatchEvent(c)},/**
  108919. * Returns a snapshot of inEvent, with writable properties.
  108920. *
  108921. * @param {Event} inEvent An event that contains properties to copy.
  108922. * @return {Object} An object containing shallow copies of `inEvent`'s
  108923. * properties.
  108924. */
  108925. 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],
  108926. // Work around SVGInstanceElement shadow tree
  108927. // Return the <use> element that is represented by the instance for Safari, Chrome, IE.
  108928. // This is the behavior implemented by Firefox.
  108929. !t||"target"!==b&&"relatedTarget"!==b||c[b]instanceof SVGElementInstance&&(c[b]=c[b].correspondingUseElement);
  108930. // keep the semantics of preventDefault
  108931. 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){
  108932. // Order of conditions due to document.contains() missing in IE.
  108933. for(var d=a.target,e=[];d!==document&&!d.contains(a.relatedTarget);)
  108934. // Touch: Do not propagate if node is detached.
  108935. 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)}},/**
  108936. * Dispatches the event to its target.
  108937. *
  108938. * @param {Event} inEvent The event to be dispatched.
  108939. * @return {Boolean} True if an event handler returns true, false otherwise.
  108940. */
  108941. 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(
  108942. // is element a shadow host?
  108943. e=this.targetingShadow(f);e;){if(
  108944. // find the the element inside the shadow root
  108945. d=e.elementFromPoint(b,c)){
  108946. // shadowed element may contain a shadow root
  108947. var g=this.targetingShadow(d);return this.searchRoot(g,b,c)||d}
  108948. // check for older shadows
  108949. e=this.olderShadow(e)}
  108950. // light dom element is the target
  108951. return f}},owner:function(a){
  108952. // walk up until you hit the shadow root or document
  108953. for(var b=a;b.parentNode;)b=b.parentNode;
  108954. // the owner element is expected to be a Document or ShadowRoot
  108955. 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);
  108956. // if x, y is not in this root, fall back to document search
  108957. 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){
  108958. // Only watch scopes that can target find, as these are top-level.
  108959. // Otherwise we can see duplicate additions and removals that add noise.
  108960. //
  108961. // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see
  108962. // a removal without an insertion when a node is redistributed among
  108963. // shadows. Since it all ends up correct in the document, watching only
  108964. // the document will yield the correct mutations to watch.
  108965. 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))},
  108966. // register all touch-action = none nodes on document load
  108967. 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){
  108968. // find children with touch-action
  108969. var b=x(a,this.findElements,this);
  108970. // flatten the list
  108971. // make sure the added nodes are accounted for
  108972. 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){}
  108973. // handler block for native mouse events
  108974. 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:[],
  108975. // collide with the global mouse listener
  108976. 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++){
  108977. // simulated mouse events will be swallowed near a primary touchend
  108978. 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);
  108979. // Update buttons state after possible out-of-document mouseup.
  108980. 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];
  108981. // Produces wrong state of buttons in Browsers without `buttons` support
  108982. // when a mouse button that was pressed outside the document is released
  108983. // inside and other buttons are still pressed down.
  108984. c.buttons=b?b.buttons&~d:0,a.buttons=c.buttons}H.set(this.POINTER_ID,a),
  108985. // Support: Firefox <=44 only
  108986. // FF Ubuntu includes the lifted button in the `buttons` property on
  108987. // mouseup.
  108988. // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366
  108989. 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),
  108990. // set touch-action on shadows as well
  108991. 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),
  108992. // remove touch-action from shadow
  108993. 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);
  108994. // simply update scrollType if listeners are already established
  108995. 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){
  108996. // set primary touch if there no pointers, or the only pointer is the mouse
  108997. (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,
  108998. // forward modifier keys
  108999. c.altKey=b.altKey,c.ctrlKey=b.ctrlKey,c.metaKey=b.metaKey,c.shiftKey=b.shiftKey;
  109000. // forward touch preventDefaults
  109001. 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))},
  109002. // For single axis scrollers, determines whether the element should emit
  109003. // pointer events or behave as a scroller
  109004. shouldScroll:function(a){if(this.firstXY){var b,c=a.currentTarget._scrollType;if("none"===c)
  109005. // this element is a touch-action: none, should never scroll
  109006. b=!1;else if("XY"===c)
  109007. // this element should always scroll
  109008. 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]);
  109009. // if delta in the scroll axis > delta other axis, scroll instead of
  109010. // making events
  109011. 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},
  109012. // In some instances, a touchstart can happen without a touchend. This
  109013. // leaves the pointermap in a broken state.
  109014. // Therefore, on every touchstart, we remove the touches that did not fire a
  109015. // touchend event.
  109016. // To keep state globally consistent, we fire a
  109017. // pointercancel for this "abandoned" touch
  109018. vacuumTouches:function(a){var b=a.touches;
  109019. // pointermap.size should be < tl.length here, as the touchstart has not
  109020. // been processed yet.
  109021. if(R.size>=b.length){var c=[];R.forEach(function(a,d){
  109022. // Never remove pointerId == 1, which is mouse.
  109023. // Touch identifiers are 2 smaller than their pointerId, which is the
  109024. // index in pointermap.
  109025. 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);
  109026. // a finger drifted off the screen, ignore it
  109027. if(c){var d=c.out,e=c.outTarget;u.move(b),d&&e!==b.target&&(d.relatedTarget=b.target,b.relatedTarget=e,
  109028. // recover from retargeting by shadow
  109029. d.target=e,b.target?(u.leaveOut(d),u.enterOver(b)):(
  109030. // clean up case when finger leaves the screen
  109031. 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)},
  109032. // prevent synth mouse events from creating pointer events
  109033. dedupSynthMouse:function(a){var b=N.lastTouches,c=a.changedTouches[0];
  109034. // only the primary finger will synth mouse events
  109035. if(this.isPrimaryTouch(c)){
  109036. // remember x/y of last touch
  109037. 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});
  109038. /***/ }),
  109039. /* 32 */
  109040. /***/ (function(module, exports, __webpack_require__) {
  109041. "use strict";
  109042. Object.defineProperty(exports, "__esModule", { value: true });
  109043. var defaultViewer_1 = __webpack_require__(5);
  109044. var mappers_1 = __webpack_require__(1);
  109045. function InitTags(selector) {
  109046. if (selector === void 0) { selector = 'babylon'; }
  109047. var elements = document.querySelectorAll(selector);
  109048. for (var i = 0; i < elements.length; ++i) {
  109049. var element = elements.item(i);
  109050. var configMapper = mappers_1.mapperManager.getMapper('dom');
  109051. var config = configMapper.map(element);
  109052. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  109053. }
  109054. }
  109055. exports.InitTags = InitTags;
  109056. /***/ })
  109057. /******/ ]);
  109058. (function universalModuleDefinition(root, factory) {
  109059. var f = factory();
  109060. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  109061. globalObject["undefined"] = f;
  109062. if(typeof exports === 'object' && typeof module === 'object')
  109063. module.exports = f;
  109064. else if(typeof define === 'function' && define.amd)
  109065. define("babylonjs-viewer", factory);
  109066. else if(typeof exports === 'object')
  109067. exports["babylonjs-viewer"] = f;
  109068. else {
  109069. root["undefined"] = f;
  109070. }
  109071. })(this, function() {
  109072. return undefined;
  109073. });